How to get json value by string? - javascript

I receive the following string from the server response:
var jsonData = '[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]';
I see some jquery plugins can predefine the keys they want
like: index:"firstName", and they get a ul like
<li>Bill</li>
<li>George</li>
<li>Thomas</li>
If index:"lastName", they get a ul like
<li>Gates</li>
<li>Bush</li>
<li>Carter</li>
The only way I know how to parse a json format string is:
var object = JSON.parse(jsonData);
var firstName = object[i].firstName;
var lastName= object[i].lastName;
The plugin pass the index like a parameter
function f(index) {
return object[i].index;
}
How can they achieve this?
Thanks for helping!

You can access object properties with square brackets. JS objects work like arrays in this regard.
var objects = JSON.parse(jsonData),
key = "firstName";
objects.forEach(function (obj) {
var value = obj[key];
// ...
});

Related

How to retrieve a specific object from a JSON value stored in sessionStorage?

I have this stored in the session:
What I'm looking to do is assign each object in the JSON as a variable so I can add them to the DOM appropriately.
This works but prints everything out:
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
$(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9')).appendTo('.div');
}
What I'd like is something like this, but it doesn't work:
var div1 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.cart-contents')));
var div2 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'a.footer-cart-contents')));
var div3 = $(JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9', 'div.widget_shopping_cart_content')));
Any help would be greatly appreciated. Thank you!
Getting the same value from the storage several times is not a good idea. In addition, you need better names for your variables.
var json = sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
if (json) {
var data = JSON.parse(json);
if (data) {
var cart_link = $(data['a.cart-contents']),
footer_link = $(data['a.footer-cart-contents']),
widget_div = $(data['div.widget_shopping_cart_content']);
}
}
So it appears you have set selectors as keys of the object so you could iterate those keys to get each selector.
The propose of those selector keys is not 100% clear. I am assuming that those selectors are the elements you want to insert the html strings into and that $() means you are using jQuery
if (sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9') != null) {
var data = JSON.parse(sessionStorage.getItem('wc_fragments_aaf6a2e5b971cb51d59e8f3eae9b34c9');
$.each(data, function(selector, htmlString){
$(selector).append(htmlString)
});
}

A quicker way to update lots of values

Im updating many fields using ajax. My server is getting a row from the database then I am JSON encoding the row and sending this as my xmlhttp.responseText.
The response text is of the form
{"JobCardNum":5063,"IssueTo":"MachineShop","Priority":"High" ...lots of data}
In the browser I then JSON parse the response text and then begin the long process of updating the values like so:
var obj = JSON.parse(info);
document.getElementById("JobCardNum").value = obj.JobCardNum;
document.getElementById("IssueTo").value = obj.IssueTo;
document.getElementById("MachineShop").value = obj.MachineShop;
....... lots of similar statements
As the element id matches the column names I though there might be a way to loop through my JavaScript object and set all my values. Any Ideas?
This code should iterate over your json object and update the values.
for (var key in p) {
if (p.hasOwnProperty(key)) {
var el = document.getElementById(key);
if(el) el.value = p[key];
}
}
The solution using Object.keys and Array.forEach functions:
var obj = JSON.parse(info);
Object.keys(obj).forEach(function(id){
var el = document.getElementById(id);
if (el) el.value = obj[id];
});

How to read a javascript object

I am using from Microsoft the
Live Connect Developer Center
It returns this type of variable for a contact but I don't know of a simple way to read it, would perform split on it but do not know how to read this object:
{"id":"contact.0d3d6bf0000000000000000000000000", "first_name":"William", "last_name":"Shakespeare", "name":"William Shakespeare", "gender":null, "is_friend":false, "is_favorite":false, "user_id":"2ae098749083cb3d", "email_hashes":["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"], "updated_time":"2012-10-04T19:23:34+0000"}
I'd need to access name and email_hashes with what's inside of it:
a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6 - without the brackets.
Just don't know how to read this kind of object.
JSON.parse() is specifically designed to take a string in JSON format and produce a JavaScript object, from which you can then access properties.
That looks like JSON. If you're using jQuery, you could do something like this:
var jsonData = $.parseJSON('{"id":"contact..."}');
alert('name: ' + jsonData.id);
See the docs for more usage examples: http://api.jquery.com/jQuery.parseJSON/
The response you're receiving is a key/value pair. You can access any value with the key
obj[key] // value
or
obj.key // value
if
var x = {"id":"contact.0d3d6bf0000000000000000000000000", "first_name":"William", "last_name":"Shakespeare", "name":"William Shakespeare", "gender":null, "is_friend":false, "is_favorite":false, "user_id":"2ae098749083cb3d", "email_hashes":["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"], "updated_time":"2012-10-04T19:23:34+0000"}
then
x.email_hashes
returns
["a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"]
and
x.email_hashes[0]
returns
"a790b818acfdef744a23bef534dfd9a4a53aa834250bdfe55f6874543129daa6"
When you get your variable with the JSON, do this:
var stringData = {}, // Incoming data
data = JSON.parse(stringData);
Then, you can access the variables like this:
var id = data.id,
firstName = data.first_name;
To access array values, do this:
var emailHashes = data.email_hashes;
if (emailHashes.length > 0) {
var i = 0;
for (; i < emailHashes.length; i++) {
// perform some action on them.
}
}

Push to array a key name taken from variable

I have an array:
var pages = new Array();
I want to push my pages data to this array like this:
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
pages_order.push({datatype:info});
});
but this code doesn't replace datatype as variable, just puts datatype string as a key.
How do I make it place there actual string value as a key name?
I finally saw what you were trying to do:
var pages = new Array();
$('li.page').each(function () {
var datatype = $(this).attr('data-type');
var info = $(this).attr('data-info');
var temp = {};
temp[datatype] = info;
pages_order.push(temp);
});
$('li.page').each(function () {
//get type and info, then setup an object to push onto the array
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
obj = {};
//now set the index and the value for the object
obj[datatype] = info;
pages_order.push(obj);
});
Notice that you can put a comma between variable declarations rather than reusing the var keyword.
It looks like you just want to store two pieces of information for each page. You can do that by pushing an array instead of an object:
pages_order.push([datatype, info]);
You have to use datatype in a context where it will be evaluated.
Like so.
var pages = [];
$('li.page').each(function () {
var datatype = $(this).attr('data-type'),
info = $(this).attr('data-info'),
record = {};
record[datatype] = info;
pages_order.push(record);
});
You only need one var it can be followed by multiple assignments that are separated by ,.
No need to use new Array just use the array literal []
You may add below single line to push value with key:
pages_order.yourkey = value;

How do I access a JSON object using a javascript variable

What I mean by that is say I have JSON data as such:
[{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]
and I want to do something like this:
var x = "ADAM";
alert(data.x.TEST);
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
x = "ADAM";
alert(data[0][x].TEST);
http://jsfiddle.net/n0nick/UWR9y/
Since objects in javascripts are handled just like hashmaps (or associative arrays) you can just do data['adam'].TEST just like you could do data.adam.TEST. If you have a variable index, just go with the [] notation.
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}]
alert(data[0].ADAM.TEST);
alert(data[0]['ADAM'].TEST)
if you just do
var data = {"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}};
you could access it using data.ADAM.TEST and data['ADAM'].TEST
That won't work as you're setting x to be a string object, no accessing the value from your array:
alert(data[0]["ADAM"].TEST);
var data = [{"ADAM":{"TEST":1}, "BOBBY":{"TEST":2}}],
x = "ADAM";
alert(data[x].TEST);
This is what worked for me. This way you can pass in a variable to the function and avoid repeating you code.
function yourFunction(varName, elementName){
//json GET code setup
document.getElementById(elementName).innerHTML = data[varName].key1 + " " + data.[varName].key2;
}

Categories

Resources