I serially collect information from forms into arrays like so:
list = {"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"};
identifier = "first_round";
list = {"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"};
identifier = "second_round";
I want to combine them into something (I may have braces where I need brackets) like:
list_all = {
"first_round" :
{"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"} ,
"second_round" :
{"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"}
};
so I can access them like:
alert(list_all.first_round.name) -> John
(Note: the name-values ("name", "email", "color") in the two list-arrays are not quite the same, the number of items in each list-array is limited but not known in advance; I need to serially add only one array to the previous structure each round and there may be any number of rounds, i.e. "third-round" : {...}, "fourth-round" : {...} and so on.)
Ultimately, I'd like it to be well-parsed for JSON.
I use the jquery library, if that helps.
Create list_all as a new object as follows:
var list_all = {};
list_all[identifier_1] = list_1;
list_all[identifier_2] = list_2;
// ...
JSON uses object literal notation. The form:
var person = {
"name": "Douglas Adams"
"age": 42
};
Is exactly the same (for all intents and purposes) as:
var person = new Object();
person.name = "Douglas Adams";
person.age = 42;
Does that help you?
You can also use
person["age"]
this is the same as
person.age
and to iterate through named properties:
//prints the person.propertyName for all propertyName in person
for (var propertyName in person) {
alert(person[propertyName]);
}
You can transmit data as a string, using it to interact with the server and converting it into an object, using jQuery. Ex:
var jsonString = "{'name': 'Douglas Adams', 'age': 42}";
jQuery.parseJson(jsonString); //returns this as an object
Search for JSON in the jQuery API docs: http://api.jquery.com/
Related
Consider the following sample document
[{
"Name" : "John doe",
"age" : 22,
"email" : "john#doe.com"
},
{
"Name" : "William",
"age" : 28,
"email" : "william#william.com"
},
{
"Name" : "jack",
"age" : 22,
"email" : "jack#jack.com"
}]
I have an array of objects with me with the following structure
[{'name':'jack','age':10},{'name':'john','age':20}]
How do I perform a query in the document in a way such that I can match the name field and age field of my array of objects of each element.
Basically, the name jack and the age 10 should query with the sample and after that the name john and the age 20 should perform the query.
I know that $elemMatch could have been used if it was the other way around where I had to query with single elements in an array. Is there any way of doing this?
If you are not talking about searching the retrieved documents. You can search database like this:
var searchArr = [{name:'jack',age:10},{name:'john', age:20}]
searchArr.forEach(function(element){
var query = Model.find(element)
query.then(function(result){
console.log(result)
})
})
I have a JSON
{
"destination_addresses" : [ "14 Mission St, San Francisco, CA 94105, USA" ],
"origin_addresses" : [ "23 Mission St, San Francisco, CA 94103, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "1.3 mi",
"value" : 2060
},
"duration" : {
"text" : "7 mins",
"value" : 444
},
"duration_in_traffic" : {
"text" : "6 mins",
"value" : 344
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}
I have been attempting to access the "text" value of duration_in_traffic and to store that value into a variable. For some reason I am getting the value to be undefined.
var hold = JSON.parse(body.rows.elements.duration.text);
Why cannot I access the child like this?
You have nested arrays, so you need to access the elements in the arrays by their index.
var hold = body.rows[0].elements[0].duration_in_traffic.text;
you need to parse the JSON string (if it is a string) first, then you can access it ... assuming body is the var that holds the string, you would do
var hold = JSON.parse(body).rows[0].elements[0].duration.text;
or
var obj = JSON.parse(body);
var hold = obj.rows[0].elements[0].duration.text;
JSON.parse does not parse part of a json string. if your json string is store in body for example, you need to parse it first:
var jsonObj = JSON.parse(body);
This will give you a javascript object to work with, then you can access the properties of the object as you have tried to do.
var hold = body.rows[0].elements[0].distance.text; //similar to #js91
Hope that helps!
In JavaScript, I have the following array of json objects and I would like to change those ticked with 'false' to 'true'. I am currently using the _.map() function in Underscore.js, is there a more efficient way of selecting the 'false' elements and only modify them?
var arrOfJson = [
{"name" : "Tom", "ticked" : false},
{"name" : "John", "ticked" : true},
{"name" : "Patrick", "ticked" : false},
{"name" : "Dave", "ticked" : true}
];
_.map(arrOfJson, function(entry){
entry.ticked = false;
return entry;
});
Thats pretty efficient. Im the author of open source project http://www.jinqJs.com. You could do something like this using javaScript LINQ expression
var result = jinqJs().from(arrOfJson).select([{field: 'name'}, {text:'ticked', value: true}]);
I am not quite clear on how to make a JSON string. I get error and I want to find out how to correct and it make it.
This is my JSON string:
var drivers = { "driver" : [
{
"id" : 1,
"name" : "Bob",
"age" : "34"
"car" : [
{
"make" : "BMW",
"model" : "3.20",
"colour" : "Silver"
}
]
},
{
"id" : 2,
"name" : "Rob",
"age" : "22"
"car" : [
{
"make" : "Peugeot",
"model" : "306",
"colour" : "Blue"
}
]
},
{
"id" : 3,
"name" : "Maria",
"age" : "23",
"car" : [
{
"make" : "Mazda",
"model" : "3",
"colour" : "Red"
}
]
}]};
This is the get method:
var driverData = JSON.parse(drivers);
function getDriverData() {
return driverData;
}
return {
getDriverData: getDriverData
};
And in this controller I try to get it so I can see if it works:
var drivers = myDriveApi.getDriverData();
console.log(driverData);
Correct me and explain how to make a JSON string, and I want it nested if that's the right term. So each driver has a car, or multiple cars/vehicles. So if I get 1 driver, I want to see his details and his information on owned vehicles.
Your "JSON string" seems to be JavaScript code that you would have in a script tag that creates a drivers JavaScript object with a property called driver that is an array of other objects. To be JSON, you remove the var drivers = and the semicolon at the end leaving just what you would set a variable to in order to create that object.
For instance, let's say you have a "person" variable that is an object with "firstName" and "lastName" properties. This is code you would put into a script to create that variable:
var person = { firstName: "Jason", lastName: "Goemaat" };
Strings, even JSON strings are represented in scripts surrounded by single or double quotes. To see the string value for the JSON of that object, you can do this:
var json = JSON.stringify(person);
This gives you a valid JSON string which will display this in the console:
{"firstName":"Jason","lastName":"Goemaat"}
To set the variable directly you need to enclose it in single or double quotes, but if the string contains those they would need to be escaped. Since this contains only double quotes I will surround it in single quotes to assign it to a variable in my script, then parse that into an object.
var json = '{"firstName":"Jason","lastName":"Goemaat"}';
var person = JSON.parse(json);
JSON property names need to be surrounded in quotes. Most parsers will work if they are not but it is always better to be as correct as you can be. You can use the online tool at jsonlint to check for valid JSON.
No, that's a JavaScript object, which could be converted to a JSON string using JSON.stringify(object).
If you're trying to access it through JavaScript, you might as well skip JSON altogether and just use the object. If you want to test if a JSON string is good, use jsonlint.com.
It's a JavaScript object, not a JSON string.
You're missing commas after Bob and Rob's age. Maria's all good, though.
If my markup looks like this:
<div data-test="{ "value" : "bar", "_id" : 1234, "name" : "john", "age" : 25 }">...</div>
<div data-test="{ "value" : "foo", "_id" : 1235, "name" : "paul", "age" : 26 }">...</div>
<div data-test="{ "value" : "drummer", "_id" : 1236, "name" : "ringo", "age" : 22 }">...</div>
How would I select a particular element using JQuery if I only had the key 'bar' or 'foo'?
I could pull out the whole object for each row and iterate through it looking for a match but I'd rather not if there is a more efficient method.
How can I cleanly select based on the property of an object?
Try this
$('div[data-test$=": bar }"]')
$('div[data-test$=": foo }"]')
More details here
UPDATE:
If attributes are not ending with bar/foo then you could try contains selector
$('div[data-test*="'value' : 'bar'"]')
$('div[data-test*="'value': 'foo'"]')
More details here
Or you could also use starts selector if it starts with value
You can use:
$("div").filter(function() {
return $(this).data("test").value == "bar";
})
jQuery.data() automatically parses a data value that's in JSON format into the corresponding object.
FIDDLE