This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed last year.
I need to process a series of data, where each line has the user ID and the data I want to process. I thought a good solution would be to read these files and create a JSON where the keys are the ids and the values are all the data associated with that id.
[
id1 :
{
name: "..."
age: "..."
date_of_birth: "..."
},
id2 :
{
name: "..."
age: "..."
date_of_birth: "..."
},
...
]
However, I'm not sure how I can dynamically add more information to the objects associated with the ID. At each reading of the line of my file, I must look in my dictionary for the ID. If there is already a record of this ID in the dictionary, I should just add a new line in the object associated with it. Otherwise, I must create this key/value pair and add a new line to the object associated with it. Preferably, I would like to build this dictionary in descending order of ids. Any idea how I can build this structure?
if one id can have several instances , it is better to use this structure
{
"id1" : [
{
name: "name1",
age: 1,
date_of_birth: "date1"
}
],
"id2" :[
{
name: "name2",
age: 2,
date_of_birth: "date2"
}
]
}
Related
I have a payload that i want to validate using JSON schema, but there this case that i don't know how to translate to a schema.
Let's say i have this object:
{
jobs: [
{ title: "Developer", salary: "100", actual: false },
{ title: "Plumber", salary: "200", actual: true },
{ title: "Teacher", salary: "100", actual: false }
]
}
i want to write a schema that validates that IF there are objects in the jobs array, one (and only one) of them MUST have the actual key set to true.
Is this possible?
Yes, it's possible. You want to set up a schema with the "items", "contains", "minContains" and "maxContains" keywords that leverage the "if"/"then" ability to write conditionals. That is, in pseudocode:
I have an object with property "jobs", whose value must be an array.
the items in that array are objects, which have properties named "title", "salary" and "actual" (with specific types for each of those values).
either the "jobs" array has zero items, or it must contain exactly one item which has a property named "actual" whose value is a constant of value true.
I am confused by reading a lot of JSON tutorials on the Internet (even on STO) and not able to decide what is right and what is wrong related to writing an external JSON file.
I have seen so many instances e.g.
(for a single object tho Adobe Dreamweaver CS5.5 shows syntax error, don't know why)
#1
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
}
#2
For multiple objects:
[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
#3
Some have been seen using single quotes around the objects array and storing the array in a variable like this:
customers = '[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]'
#4
A few of them writing above code in the following style:
{
"customers" : [
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
}
#5
One more extra sample format added:
{
[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
}
To be honest, I am totally confused and can't figure out which one is correct and standard style for writing an external .json file (especially those having multiple objects).
So I am asking all my questions here:
What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.
How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?
In which standard format, the third parties APIs present json data?
What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.
You can't use variables in a JSON-file. The third example is probably some snippet of JSON being assigned to a variable within some application.
How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?
You can start and end the file with square brackets ([ ... ]) if you want to specify an array of multiple objects. If you start and end the file with curly brackets ({ ... }), you specify one top-level object (without a key).
However, you can embed arrays in objects, or include layers of objects. So your last example is indeed valid JSON. Read it as: a top level object, that itself has one attribute 'customers', which contains an array of more objects.
As per its name: JSON = JavaScript Object Notation.
It deals with only 2 things:
Javascript object(s) with any functions stripped out. An object can contain one or more name: value pairs, comma separated. Hopefully you can see that an object is denoted by the presence of { ... }
The JSON definition calls these name/value pairs 'members'. A member name has a colon after the name, so it can be represented as:
{ "name": value }
Value can be any basic javascript type, which are basically object, string, boolean, null OR an array. The safest way to do this so that's maximally interoperable/interchangeable is to always enclose the name in quotes, but it's not strictly necessary to be acceptable json.
So with several properties:
{
"name": "Bob",
"age": 3,
"likes": ["eggs", "ham"],
"parents": [{ "name": "Wilma"}, {"name": "Fred"],
"deleted": false
}
Javascript array
An array is an ordered (ie. 0..n) list of valid json types.
[ 3, "Hello", { "firstname": "Joe", "lastname": "Dimaggio" }, [ 0, 1, 2], true ]
In javascript, you can enclose a string using either single quotes or double quotes, but in json you must always use double quotes.
This won't pass json validation:
{ "name": 'Homer' }
That is all there is to it. An object has a name and a value that could be anything including another object or an array.
Objects are denoted with {} and arrays are denoted with []
Reading a static file is another issue entirely.
With PHP you use json_decode(). That's simple other than whether you want json objects to be turned into php objects, or nested associative arrays where the javascript object property names become the keys of the array. It defaults to making objects, and frequently that's more complicated than an array.
With Javascript often people just want to use the data easily, with the various issues and workarounds illustrated in the linked question.
I've never asked a question on here but here goes.
Lets say I have an array (named whatever) that looks like this when displayed:
[[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]]
And I want to do something like whatever[1].price (this fails in my program) I want to be able to take one of the arrays in whatever and retrieve it like whatever[1].price. Any way to do this similar to an ArrayName[index].key ?
first, your JSON is not correct, see the updated one;
since inner element of array is an array with single item so you can access it with 0 index.
var test = [[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]];
test.forEach(item=> {
console.log(item[0]['price'])
});
Why does an Array of Objects be stored in an another array? Just remove the extra array initialization if you just want to achieve this
And I want to do something like whatever[1].price
Change the data like this:
[{name: "Joe", price: 42}],[{name: "Smith", price: 34}],[{name: "Jerry", price: 67}]
If you can't change the data, then A.T.'s solution will suffice
Well, based on your response ( which have an unnecessary array which contain an array of objects ) you can access to your data like
whatever[0][0].price
The better way is to change your response in backend to get an array of objects then you can access it like normal
whatever[0].price
This question already has answers here:
Retrieve only the queried element in an object array in MongoDB collection
(18 answers)
Closed 4 years ago.
Given the following JSON example:
{
_id: "55ef729a66d78d24008xxxx",
name: "The right one"
items: [{
_id: "55ef729a66d78d24008xxxx",
return: true
}, {
_id: "55ef729a66d78d24008xxxx",
return: true
}, {
_id: "55ef729a66d78d24008xxxx",
return: false
}]
}
I want to write a query that specifies items.return = true and it should return:
{
_id: "55ef729a66d78d24008xxxx",
name: "The right one"
items: [// 2 element array]
}
I've seen a lot of people suggest using $elemMatch, such as this question, but as it says, this
only return the first match
but this just returns the parent documents that have some value in the array matching items.return. So in the above example it would return all 3 array elements.
I want to completely ignore these array values in my return. I don't want to do it in the client, because I do a project using the items _id and don't want to waste the project if I don't need it.
Alternative not exact you want
db.items.aggregate(
{$unwind:"$items"},
{$match:{"items.return":true}}
)
One alternative is to use $elemMatch. Check the docs, worth to notice is that it only returns first match!
db.items.find({}, {items: {$elemMatch: {return: "admin"}}}});
You can use the aggregation framework, it is not the best solution though
db.collection.aggregate([
{$unwind:'$items'},
{$match:{'items.return':true}},
{$group:{_id:'$_id', name: '$name',items:{$push:'$items'}}}
])
Despite much googling and hair-pulling, I can't for the life of me articulate the difference between json, objects, and arrays (in javascript). Below is how I've been using 2-dimensional data containers (afraid to use the words "array," "object," or "json" here). Please tell me what these two examples are?
//first example:
[
{"record_id":1,"name":"Frank"},
{"record_id":2,"name":"Sally"}
]
//second example:
{
"countries":
[
{"id":1,"name":"Canada"},
{"id":2,"name":"Mexico"}
],
"states":
[
"id":1,"name":"Maine"},
{"id":2,"name":"Alaska"}
]
}
JSON is a representation of the data structure, it's not an object or an array.
[1,2,3]
is an array.
{"foo":"bar"}
is an object.
In your example,
[
{"record_id":1,"name":"Frank"},
{"record_id":2,"name":"Sally"}
]
Is an array of objects.
{
"countries":
[
{"id":1,"name":"Canada"},
{"id":2,"name":"Mexico"}
],
"states":
[
{"id":1,"name":"Maine"},
{"id":2,"name":"Alaska"}
]
}
Is an object containing other arrays and objects inside of it.
JSON is JavaScript Object Notation. This is simply a way of writing down JavaScript data types. It is not a data type in-and-of-itself.
See below for some examples of JavaScript data types, and the literal notation of creating them.
JSON can be used to send data from the server to the browser, for example, because it is easy for JavaScript to parse into a normal JavaScript data structure.
In your example, you are using lists of objects, and objects of objects.
This is a list of 3 empty objects.
[{}, {}, {}]
This is a list of three simple records:
var mylist = [
{name: 'John', age: 24},
{name: 'Bill', age: 42},
{name: 'Jill', age: 18},
]
You can access it like this:
mylist[1].name
>>> 'Bill'
mylist[2].age
>>> 18
JavaScript has several data types:
Number
1
100
-2000
123.45
String
"Hi John"
"Message:\nGo Forth"
Boolean
true
false
Array
[1,2,3]
[]
["a", "b", 123]
["a", "b", 123, [3,4,5]]
Object
{}
{a: 10}
{mylist: [1,2,3], yourlist: [4,5,6]}
{myself: {name: 'me', age: 10}, yourself: {name: 'you', age: 20}}
You use { braces } to declare an object literal.
You use [ square brackets ] to declare an array literal.
Objects are collections of key name value pairs.
Here's an example of an array of strings:
var a = [ "one", "two", "three" ];
Here's an example of a simple object that represents a person:
var personObject = {
name: 'Joe',
age: 25,
hometown: 'New York'
};
JSON is a textual data interchange format. As its name ("JavaScript Object Notation") suggests, it originates from JS; meaning that JSON is actually syntactically valid JavaScript. In other words, you can paste a JSON string directly into your JS code.
Arrays are special Objects. They can be constructed by [].
Objects can be constructed via {}.
So what you have in your example is two JSON strings, one representing an Array of objects, the second one representing an Object whose properties are themselves Arrays of Objects.
Well i believe objects can have methods and properties while arrays cant. JSON can be passed to the server while array cant be, unless you pass it as a string by POST