How to read a javascript object - javascript

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.
}
}

Related

How to get json value by string?

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];
// ...
});

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Javascript Form: Only Changed Fields

I have a php-site with a form on which i output preselected values via php. On form submit I want to check which values have changed and just submit these via javascript.
These are the preselected values I passed over from php. It's important that I keep the associative array structure.
var pbData = jQuery.parseJSON("{
"GameMode":"DEATHMATCH",
"Current Map":"VEGAS JUNKYARD",
"Current Missions":["VEGAS JUNKYARD","VILLA","PRESIDIO","KILL HOUSE","MURDERTOWN","CQB TRAINING","STREETS","THREE KINGDOMS CASINO","IMPORT\/EXPORT;"],
"RoundDuration":"3 minutes"}");
I marked the error in the code.
<script>
function displayVars(){
var form = document.getElementById('settings');
var elems = form.elements;
var txt = "";
for (var index = 0; index < elems.length; index++){
var selIndex = elems[index].selectedIndex;
if (typeof selIndex !== "undefined"){
//the Index Name in the json-object and the name of the form-field are the same
var idxName = elems[index].name;
//HERE is the problem. I want to access the subobject via a variablename, so i can iterate through it, but that doesnt work.
console.log ("pbData default = "+pbData.idxName); //always undefined
if (elems[index].value !== pbData.idx_name){
//building a POST-Url
txt = txt + elems[index].name + "=" + elems[index].options[selIndex].value+"&";
}
}
}
console.log (txt);
return false;
}
</script>
I know that I could do this differently, also with jQuery. In my case as I have the preselected values as a php-variable in any case, i think it's easier like this.
I would really like to know how I can iterate through the subobjects via a variable that contains the object names.
This is due to how you'e trying to access the property of the (JSON) object. Consider
var o1 = {idxName: true},
o2 = {foo : 'bar'},
idxName = 'foo';
o1.idxName; // true
o2.idxName; // undefined
o2[idxName]; // 'bar'
You need to access the property via pbData[idxName].
Additionally, you're not escaping quotes in your JSON string, and line breaks need to be escaped as follows
var pbData = jQuery.parseJSON("{\
\"GameMode\":\"DEATHMATCH\",\
\"Current Map\":\"VEGAS JUNKYARD\",\
\"Current Missions\":[\"VEGAS JUNKYARD\",\"VILLA\",\"PRESIDIO\",\"KILL HOUSE\",\"MURDERTOWN\",\"CQB TRAINING\",\"STREETS\",\"THREE KINGDOMS CASINO\",\"IMPORT\/EXPORT;\"],\
\"RoundDuration\":\"3 minutes\"}");
In Javascript you could keep an object or array with initial values and only post those values that are changed.
But in fact, I would do something similar, but in PHP. You can keep the original values in the session and compare the posted values to those initial values to see what has changed. That way, you won't depend on Javascript. Not only may Javascript be disabled, but also, a fast user may theoretically post the form before the Javascript has run. To move this check to PHP eliminates that risk.

How to use javascript or jquery to read a single value in json

suppose I have a function:
function getLayerInfo(uuid, top, left, index, pindex) {
this.uuid = uuid;
this.top = top;
this.left = left;
this.index = index;
this.pindex = pindex;
}
then I use json menthod in json.js:
var layer = new getLayerInfo('abc', 123, 456, 4, 5);
var layerjson = layer.toJSONString();
console.log(layerjson );
It have show the correct result,
So if I want restore the json to array or something else,or what should I do?
Or what I want is just need the "index" property value?
What should I do?
Thank you
If your using jQuery do this:
var result = $.parseJSON(layerjson);
jQuery is recommended because it will use the best and fastest method to parse the JSON string (First trying to run browser parser and then, if unavailable, javascript/built in parsers)
if not using jQuery just run this (it uses browser parser, but be careful with older browsers, make sure it exists):
var result = JSON.parse(layerjson);
Try using JSON.parse on your layerjson variable:
var obj = JSON.parse(layerjson);
alert(obj.index);
Use .parseJSON() method to convert the string back to object.
var layerObj = layerJSON.parseJSON();
layerObj.index will give you the value of the property.

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