Need help traversing JSON object in Javascript - javascript

I have code that calls a WCF service and returns a JSON string to the client. Below is the javascript function I am trying to use to parse the JSON but can not figure out how to traverse it.
Here is the function
loadDropDown: function(result, ddl, defaultItem) {
var _data = result.get_object();
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;
}
Here is the JSON
{
"d": "[{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Lexus\",\"Value\":\"Lexus\"},{\"Attributes\":{\"Keys\":[],\"Count\":0,\"CssStyle\":{\"Keys\":[],\"Count\":0,\"Value\":null}},\"Enabled\":true,\"Selected\":false,\"Text\":\"Acura\",\"Value\":\"Acura\"}]"
}
any suggestions on why this is not working? Note: I am not using jquery in the solution.

You shouldn't be generating that json. Instead, you should be outputting
{
"d": [{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Lexus","Value":"Lexus"},{"Attributes":{"Keys":[],"Count":0,"CssStyle":{"Keys":[],"Count":0,"Value":null}},"Enabled":true,"Selected":false,"Text":"Acura","Value":"Acura"}]
}
(quotes removed from "d" value)
There's no reason to convert json to a string before putting it in a json object! Just put the json straight in.

You should be able to just eval() the object (or use JSON parsing from Crockford) and access your properties in regular object notation. You may need to unescape your identifiers first, though.

You need to do eval(_data) before you use it as a javascript array.
for ex:
var _rawdata = result.get_object();
var _data = eval(_rawdata);
//Sys.Serialization.JavaScriptSerializer.deserialize(result, true);
this.clearDropDown(ddl);
this.createOption(ddl, defaultItem, '');
for (var i = 0; i < _data.length; i++) {
var _item = _data[i];
var _option = this.createOption(ddl, _item.Text, _item.Value);
}
ddl.disabled = false;

Related

Get JSON data after it's stored in a variable

After getting JSON back from the ajax call, the data "response" is stored in the "theObj" variable; however, when I try to log "theObj" to the console, it results in multiple "[Object object]", even with JSON.stringify().
If I do a "theObj[0]" (response.results[0] works fine), I get "[", for the first character in "[Object object]".
Q: How can I store JSON in a variable and get the data back out afterward?
$.ajax(settings).done(function(response) {
for (var i = 0; i < 19; i++) {
//creating JSONenter[enter image description here][1]
theObj += response.results[i];
if (i == 18) {
//console.log(theObj.id)
console.log(JSON.stringify(theObj[0].id))
}
}
}
I think the error is in the line
theObj += response.results[i];
So try this instead
function (response) {
var list = response.results;
// if there is no reason for having 19, replace this with var end = list.length
var end = Math.min(list.length, 19);
for(var index = 0; index < end; index++) {
theObj.push(list[index]);
}
console.log(theObj);
}
We don't see the initialization of theObj variable
If it is an array you should use the push function to add elements to it
If it is a common object then use theObj[id] = list[index];
DISCOURAGED If it is a string then you should use theObj += JSON.stringify(response.results[i];) + ", ";, then make sure that you add } or ] at the end if it is an object or array respectively (and that it has also has { or [ in the begining) and then use JSON.parse(theObj) to convert it back to an object
Please let me know which of the above are you using
try this
$.ajax(settings).done(function(response) {
$.each( response, function( key, val ) {
console.log(val.id)
});
}
I assumed you want to get the data as object and not a string.
For that you have to use var object = JSON.parse(yourJSONString). This method returns an object based on your JSON string.
Example:
JSON result:
{
"name":"John Doe"
}
Javascript code:
var john = JSON.parse(result);
console.log(john.name); //prints John Doe

Turn a json object string into value

I am writing a function that takes a string, splits it, and the uses json[key][key2][key3] formatting. The problem is n is potentially infinite (not literally but needs to written that way)
function getJsonValue(json,string) {
var vals = string.split(".");
var x = vals.length;
var string = '';
while (x != 0) {
string += "['"+vals[(vals.length-x)]+"']"
x--
}
return string;
}
That will produce, for example: "['condition']['item']['condition']['temp']"
I need to extract a value from that by attaching it to a json object, like
json"['condition']['item']['condition']['temp']"
But I don't know how or if that is even possible.
Edit:
The problem is I need any value from a config file to be passed in and then parsed from a returning function. I.e. User knows the value will be condition.item.condition.temp for this specific query. I am trying to write one function that covers everything and pass in config values for what I know to be the output. So, on one query, I might want the condition.item.condition.temp value and on another I might want condition.wind.chill .
I'm not sure if I understand 100% what you're trying to do, but if you're receiving a JS object json and a string in the format field1.field2.field3 and trying to get the value of json.field1.field2.field3 then you can do something like this:
function getJsonValue(json,string) {
var vals = string.split(".");
for (var i = 0; i < vals.length; i++) json = json[vals[i]];
return json;
}
It would work like this for a given object:
var obj = { field1: { field2: { field3: "Hello!" } } };
var res = getJsonValue(obj, "field1.field2.field3");
console.log(res); // prints Hello
See lodash get
_.get(json, 'key1.key2.key3')
you can build the "path" from your current code and ask lodahs to get the value out for you.
What about doing an eval?
var json = {
'one': {
'two': {
'three': {
'four': 4
}
}
}
};
alert(eval("json['one']['two']['three']['four']"))

How to parse read json elements with jquery

I have to create cart system in my mobile application, i want to store the id and the quantity of products, the id should be the key of my array (for modifying product quantity) , tried to use object instead of array but i get error: undefined is not a function when i try to read my json variable
by JSON.stringify(cart)
My cart code is like this
var cart = [];
var produit = {};
produit['qte'] = $('.'+id_prd).text();
produit['id_produit'] = id_prd;
cart[id_prd] = produit;
window.sessionStorage["cart1"]= JSON.stringify(cart);
return me
{"7":{"qte":"1","id_produit":7},"8":{"qte":"1","id_produit":8}}
when I tried to parse the json string with
var parsed = $.parseJSON(window.sessionStorage["cart1"]);
i get the error 'undefined is not a function'
when triying to read the json with
var i=0;
for (k in parsed) {
var k_data = parsed[k];
k_data.forEach(function(entry) {
alert(entry);
ch+=entry.id_produit;
if(i<parsed.length-1)
ch+= ',';
if(i==parsed.length-1)
ch+=')';
i++;
});
}
Can you clarify me the error cause, and if there's a solution to better read the json
The problem is that you are using k_data.forEach(function(entry) but forEach is for Arrays, and k_data is just a simple javascript object.
Try changing:
k_data.forEach(function(entry){
to this:
$(k_data).each(function(entry){
Even more, if the JSON is always in the same structure you posted, I think the each function is not necessary, maybe this is the way you are looking for:
var i=0;
var ch = "(";
for (k in parsed) {
var k_data = parsed[k];
alert(k_data);
ch+=k_data.id_produit;
ch+= ',';
i++;
}
ch = ch.substring(0, ch.length - 1) + ")";
You shouldn't need jQuery for this. The same JSON object you used to stringify has a parse function:
var parsed = JSON.parse(window.sessionStorage["cart1"]);
If that still breaks, there's probably something wrong with another undefined object.
You can try something like this:
<script type="text/javascript">
var finalArr = new Array();
var dataArr = new Array();
dataArr = window.sessionStorage["cart1"];
if (JSON.parse(dataArr).length > 0) {
for (var i = 0; i < JSON.parse(dataArr).length; i++) {
finalArr.push((JSON.parse(dataArr))[i]);
}
}
</script>

Find specific key value in array of objects

This is the code:
var groups = {
"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}
I want to get the name value where the id is "qb45657s" how could this be accomplished? I figured the obvious loop through all of the array and check if it's equal but is there an easier way?
Edit: I cannot change "Array" to an object because I need to know the length of it for a different function.
You can simply filter on the given id:
groups["JSON"]["ARRAY"].filter(function(v){ return v["id"] == "qb45657s"; });
This will return [{"id":"qb45657s","name":"Use me."}]
Assuming you had a valid JSON string like this (note I say valid, because you need an enclosing {} or [] to make it valid):
var json = '{"JSON":{
"ARRAY":[
{"id":"fq432v45","name":"Don't use me."},
{"id":"qb45657s","name":"Use me."}
]
}
}';
You would just parse it into an actual object like this:
var jsonObj = JSON.parse(json); // makes string in actual object you can work with
var jsonArray = jsonObj.JSON.ARRAY; // gets array you are interested in
And then search for it like:
var needle = 'qb45657s';
var needleName;
for (var i = 0; i < jsonArray.length; i++) {
if (jsonArray[i].id === needle) {
needleName = jsonArray[i].name;
}
}

Can not parse JSON with JavaScript parser. Square brackets

I using JavaScript JSON library to parse JSON encoded array, received via POST.
Here is my code:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = JSON.parse(itemsRequest);
for(var i = 0; i<items.count(); i++)
{
var item = items[i];
alert(item.id);
}
I am not sure why, but the parser is just not liking that. How can I get it to parse?
Try items.length instead of items.count().
An array doesn't have a count method. Use the length property:
for (var i = 0; i < items.length; i++) {
Demo: http://jsfiddle.net/Guffa/Rt4db/
Below is the very good way to do:
var itemsRequest = '[{"id":"142"},{"id":"152"}]';
var items = eval(itemsRequest); //Converted to actual JSON data
for (var item in items) {
alert(items[item]['id']);
}
Hope this is very helpful, thanks

Categories