Json associative array accessing in jQuery - javascript

I am getting response in below format for every product and in a single call there can be many products. I am trying to access this data via jQuery but I'm not able to access it.
Productdata['someid'] = { "Product Json data"}
I am using below syntax in jQuery but not getting the data. Please suggest.
alert(Productdata['someid']);

Its not going as JSON format .
JSON is a key : value pair format ;
so your Productdata should be in below format:
Productdata = { 'someid' : "Product Json data"}

A Json like this
var data={"name":"somebody"};
To call
return data.name
Or
return data["name"]

The problem here is that JavaScript does not support associative arrays (scroll down to "Associative arrays, no way!"). It has some internal workarounds which make it appear as if it does, but really all it does is just adding the keys as properties.
So you would most likely be able to access it using Productdata.someid = ....
EDIT:
So assuming you have the following JSON string: {"id":"123"} (which is valid JSON), you can use it like this:
var jsonString = '{"id":"123"}';
var parsedJSON = $.parseJSON(jsonString);
var productID = "product_" + parsedJSON.id;
Does this help?
Some useful links: JSON format checker to make sure the JSON is valid.
Unfortunately I wasn't allowed to add more than 2 links, so the jQuery parseJSON function link is still in the comment below.

Related

Json Keys Are Undefined When Using Them From Script Tag

I've been trying to load certain Json with Ajax GET request and then parsing it.
However when trying to access the Json key from HTML script tag it was undefined.
In order to debug this issue, I logged all the keys of Json in console as well as the Json itself. Therefore i utilized this function:
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, "); // Explanation is below
console.log(invList[0]) // Just testing with first object
console.log(Object.keys(invList[0]));
});
}
getInv();
Purpose of data.split(",, "):
Since my backend script uses different programming language, I had to interpret it to the one suitable for Javascript.
There also were multiple Json objects, So i separated them with ",, " and then split them in Javascript in order to create a list of Json objects.
After calling the function, Following output was present:
Although the interesting part is that after pasting Json object in console like this:
This was the output:
So basically, in script tag, i was unable to access object's keys, although once i used it manually in console, all keys could be accessed.
What could be the purpose behind this? It seems quite strange that different outputs are given. Perhaps invList[0] is not Json object at all in the script tag? Thanks!
data.split() returns an array of strings, not objects. You need to use JSON.parse() to parse the JSON string to the corresponding objects.
function getInv() {
$.get( "/inventory/", function( data ) {
var invList = data.split(",, ");
console.log(invList[0]) // Just testing with first object
var obj = JSON.parse(invList[0]);
console.log(Object.keys(obj));
});
}
You can use .map() to parse all of them, then you'll get an array of objects like you were expecting:
var invList = data.split(",, ").map(JSON.parse);

Adding an Individual JSON Object to an Array to Parse and Process

I have the following json object samples, i.e.:
{"id":"value1" , "time":"valuetime1"}
{"id":"value2" , "time":"valuetime2"}
{"id":"value3" , "time":"valuetime3"}
{"id":"value4" , "time":"valuetime4"}
{"id":"value5" , "time":"valuetime5"}
{"id":"value6" , "time":"valuetime6"}
{"id":"value7" , "time":"valuetime7"}
{"id":"value8" , "time":"valuetime8"}
Based on the above, I would like to add all these json objects to an array, where I can then process and access the array for each json object and extract id1 value together with time1 value and so forth.
I believe I have to use JSON.parse but unsure of how to firstly add these objects to an array and then be able to also parse and access each object's data.
Think of each row above as a separate JSON object which I would like added to an array that is parsed.
Read the file line by line (each line is a separate json)
Parse the line json text to JavaScript object
Put/push/append JavaScript object into a JavaScript array
This is not valid JSON, so JSON.parse would not work, but assuming you have the text in a string variable, you can convert it to JSON with something like:
data = "[" + data.replace(/\}/g, "},").replace(/,$/,"") + "]";
and then parse it.
UPDATE:
var array = [];
// for each input line
var obj = JSON.parse(line);
array.push(obj);
var id = obj.id;
var time = obj.time;
...
Appreciate the responses but I believe I have managed to solve my own question.
Furthermore, as #Mr. White mentioned above, I did have my property names in error which I have now sorted - thanks.
Using the data above, all I was after was the following:
UPDATED
var s = '{"id":"value1","time":"valuetime1"},{"id":"value2","time":"valuetime2"},{"id":"value3","time":"valuetime3"},{"id":"value4","time":"valuetime4"},{"id":"value5","time":"valuetime5"}, {"id":"value6","time":"valuetime6"},{"id":"value7","time":"valuetime7"},{"id":"value8","time":"valuetime8"}';
var a = JSON.parse('[' + s + ']');
a.forEach(function(item,i){
console.log(item.id + ' - '+ item.time);
});
Thanks for the heads up #torazaburo - have updated my answer which I should've done much earlier.

Converting json array to query string gives null

What I am trying to achieve is to send a json object as a querystring to an API.
The json object I have is:
{
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
}
I would like to convert this to something like ?Name=&ImageUrls=
However, when using $.param(json) I get the following:
?Name=Dlsajdsa&ImageUrls%5B%5D=%2FImages%2FFacility%2F8353%2F85e26a18-4366-4412-b37a-72d94f2ccda5.jpg
This result, on the API point of view, that the ImageUrls array is null.
What am I missing here?
you can try $.param(json,true)
Based on the documentation of jQuery.param, I'd say this is the piece of code you want to use:
var json = {
"Name":"Dlsajdsa",
"ImageUrls":["/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"]
};
var recursiveDecoded = decodeURIComponent($.param(json));
// "Name=Dlsajdsa&ImageUrls[]=/Images/Facility/8353/85e26a18-4366-4412-b37a-72d94f2ccda5.jpg"
The query parameter is called ImageUrls%5B%5D, that means ImageUrls[], not ImageUrls as you expect.

Javascript: Parse JSON output result

How can i retrieve the values from such JSON response with javascript, I tried normal JSON parsing seem doesn't work
[["102",true,{"username":"someone"}]]
Tried such codes below:
url: "http://somewebsite.com/api.php?v=json&i=[[102]]",
onComplete: function (response) {
var data = response.json[0];
console.log("User: " + data.username); // doesnt work
var str = '[["102",true,{"username":"someone"}]]';
var data = JSON.parse(str);
console.log("User: " + data[0][2].username);
Surround someone with double quotes
Traverse the array-of-array before attempting to acces the username property
If you are using AJAX to obtain the data, #Alex Puchkov's answer says it best.
So the problem with this is that it looks like an array in an array. So to access an element you would do something like this.
console.log(obj[0][0]);
should print 102
Lets say you created the object like so:
var obj = [["102",true,{"username":someone}]];
this is how you would access each element:
obj[0][0] is 102
obj[0][1] is true
and obj[0][2]["username"] is whatever someone is defined as
From other peoples answers it seems like some of the problem you may be having is parsing a JSON string. The standard way to do that is use JSON.parse, keep in mind this is only needed if the data is a string. This is how it should be done.
var obj = JSON.parse(" [ [ "102", true, { "username" : someone } ] ] ")
It depends on where you are getting JSON from:
If you use jQuery
then jQuery will parse JSON itself and send you a JavaScript variable to callback function. Make sure you provide correct dataType in $.ajax call or use helper method like $.getJSON()
If you getting JSON data via plain AJAX
then you can do:
var jsonVar = JSON.parse(xhReq.responseText);

How to use the json?

I have called an api using href from the html form and it in response gives json as output.
consider this as the json the api gives
{
"entry":
{
"id": "1",
"name": "SA"
}
}
I want the values of the id and name.
How can i get the values specifically and store those values to a variable.
Also i got to do this in the html form with javascript.
I want the values of the city_id and city_name. How can i get the
values specifically and store those values to a variable
Use JSON.parse to convert it to JS object and get your values:
var obj = JSON.parse(yourJSON);
var city_id = obj['entry']['city_id'];
var city_name = obj['entry']['city_name'];
Docs:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/parse
var a;
eval('a={"entry":{"#collection_url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f4602e2c000016","#created_at": "2012-06-21T09:12:40Z","#trash": false,"#type": "City","#updated_at": "2012-06-21T09:12:40Z","#url":"http://api.storageroomapp.com/accounts/4fe004c598f46026cc000002/collections/4fe0063798f460e2c000016/entries/4fe2e58898f4604757000006","#version": 1,"city_id": "City_001","city_name": "London"}}');
in other words
eval ('a={/*response object*/}')
now you have (a) as object that contains your data you can access them whether like object notation (a.entry) or as an array (a['entry'])
you can also use json parse but its not compatible with all browsers
Either the eval() function or the JSON parser will allow you to create an object from the JSON and then access the fields normally. The JSON parser is a little more secure, as explained in this tutorial:
http://www.w3schools.com/json/json_eval.asp

Categories

Resources