How to get json value in js code? - javascript

I have a json code and i want get json value units_num in alert jQuery. How can don it?
My json code:
[{"id":"11","name":"hiih","units_num":00}]
I tried as in js code: http://jsfiddle.net/Wj8ZL/
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":00}]');
alert(obj['units_num']); // This don't work
var t = JSON.parse('[{"id":"11","name":"hiih","units_num":00}]');
alert(t['units_num']) // This don't work

Your json contains an array of objects, even if there is only one in there. So you need to access that first object in the array
var obj = $.parseJSON('[{"id":"11","name":"hiih","units_num":"00"}]');
alert(obj[0]['units_num']);

#TravisJ gave a big part of the issue, the other one being quite easy to spot if you read the error log:
"units_num":00
is not valid. It should read
"units_num":0

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

loop in JSON with undefined elements

I am trying to figure out how to retrieve the values of a json of which i do not know the number of elements.
Example:
my json can be something like
var json = ["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement4":"value4","variableelement5":"value5"]
or
var json =["fixelement1":"value1","fixelement2":"value2","fixelement3":"value3","variableelement7":"value7","variableelement8":"value8", "variableelementN":"valueN"]
the only thing that I know is that the first 3 elements are always the same.
I use .indexOf() to search a value in fixelement3. What I would like to do is, if I find the element, I would like to retrieve the name of all the following elements (which number is variable and that are unknown) and their values.
javascript or jquery would work for me, but I have no idea..
thank you in advance!
var json ={
"fixelement1":"value1",
"fixelement2":"value2",
"fixelement3":"value3",
"variableelement7":"value7",
"variableelement8":"value8",
"variableelementN":"valueN"
}
for(prop in json){
console.log('key ======> value', prop, '=====>', json[prop]);
}

fail to get json object in javascript from php

I am trying to pass json string to javascript from php, so at first i did
<div id="picker" data-dates=\''.json_encode(unserialize($a->available_datetime)).'\'></div>
and then, i try to grab it in jquery
if($("#picker").length){
available = $("#picker").attr("data-dates");
}
However, it seems it then fail to loop through the object to get key and val
$.each(available,function(key,val)
{}
It keep getting error of
var length = !!obj && "length" in obj && obj.length,
Tried for several hours now, cant find a solution to solve. Anyone can help? Thanks.
Use $("#picker").data("dates") it will get the data stored in the attribute data-dates and convert it to JSON, assuming you have a JSON string in that attribute.
Then use:
for (var i in available) {
//do something with available[i]
}
check example: https://jsfiddle.net/fud6sfjo/

Json associative array accessing in jQuery

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.

JSON to JQuery: What am I doing wrong?

I'm fairly new to javascript and jquery development. I have a table of values I'm fetching in PHP and formatting as a JSON string, because JSON looks like a great way to get data into javascript. But I'm having trouble addressing the javascript variable.
The JSON data is in a very simple format. It looks like this:
[
{"id":"1","name":"Bob","haircolor":"brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
And so on. None of the entries are complex. It's just flat rows of data.
I'm using $.getJSON() from JQuery to place the data in a variable like so:
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people.push(data);
});
According to console.log(data), the object 'data' is getting populated with the contents of my JSON string. But the push is generating these errors in the javascript console:
Uncaught TypeError: Cannot read property 'length' of undefined
Uncaught TypeError: Cannot call method 'push' of undefined
What am I missing? And is there any other information you need to help me on this? I've ground to a halt on this project because of this problem, and I'm just too much of a javascript newbie to figure it out.
The variable people must be an array. Change the first line to
var people = [];
At the moment "people" is just undefined and the .push() method only works on arrays.
If your PHP writes the output like this:
[
{"id":"1","name":"Bob","haircolor":"brown"},
{"id":"2","name":"Carol","haircolor":"Red"}
]
You need to assign that whole structure to people:
var people;
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
people = data;
});
// note that you can't access anything inside people here
// only when the json has been processed
Try defining your variable as an array before you push to it:
var people = new Array();
try initializing people variable as an array
var people = []
You can try this:
$.getJSON("php/getpeople.php", function(data){ //getpeople.php generates the JSON
$.each(data, function(i, people){
console.log(people);
});
});

Categories

Resources