How do I access a JSON object using a javascript variable - javascript

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

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

Json string values in javascript

I have following JSON string in a global variable in Javascript
var domains = {
"DomID00001": {
"ID":"DomID00001",
"Name":"Testdomein1"
},
"DomID00002": {
"ID":"DomID00002",
"Name":"Testdomein2"
}
};
What is the best way to retrieve the values from this JSON string and be able to use them in Javascript individually?
If I just alert the domains var it says = [object Object]
Using alert() will not show you objects, this is one of the big advantages of the console. Check this fiddle and use the console (pressing F12 on your browser). Then you understand how to refer to what is inside that object.
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
console.log(domains);
console.log(domains.DomID00001);
console.log(domains.DomID00001.ID);
Since the keys are variable, you should probably use a for..in loop:
for( domid in domains) if( domains.hasOwnProperty(domid)) {
console.log(domid,domains[domid].ID,domains[domid].Name);
}
Try this:
var domains = {"DomID00001":{"ID":"DomID00001","Name":"Testdomein1"},"DomID00002":{"ID":"DomID00002","Name":"Testdomein2"}};
var strName1 = domains.DomID00001.Name;
var ID1 = domains.DomID00001.ID;
alert('Name: ' + strName1 + ' - ID: ' + ID1);

Use javascript variable as array index

I have following code:
var n = 1;
var term = "${abc[n].term}";
console.log("term = " + term);
term seems to be empty, but if I replace
var term = "${abc[n].term}";
by
var term = "${abc[1].term}";
it works.
It looks like jsp is looking for the n property of the deck object, how could I fix it so that n is replaced by its value when I use is as array index ?
Edit:
It seems that it's not a good idea to try mixing JSTL and Javascript, and that if you want to use a javascript variable as array index, you must copy the object to an Array object, like this:
var deck = new Array();
<c:forEach var="v" items="${abc}">
deck.push("${v.term}");
</c:forEach>
var n = 1;
console.log("term = " + deck[n]);
You are not using quotes properly, try this:
var term = "${abc[" + n +"].term}";
"${abc[n].term}" here n is considred as a part of the string not as your variable n. So try concatenating it.

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

JSON conversion issue

I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');

Categories

Resources