JSON to JQuery: What am I doing wrong? - javascript

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

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

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.

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.

How to get json value in js code?

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

I'm getting undefined when trying to iterate through my json

I'm trying to get a JSON response and iterate through the data. Here is the response I get:
[{"category":{"category":"sell"},"subcategory":{"subcategory":"cars"}}]
Then I run that through JSON.parse() and then when I try to access data I get undefined.
for (var category in myJson) {
console.log(category.category); //this is undefined
}
Does anyone have any ideas on why this isn't working as I am intending to? Is my JSON format incorrect?
Try this:
for(var i in myJson)
console.log(myJson[i]);
Your code is wrong because you're trying to access the 'category' property of the iterator variable.
You're writing category.category where you need myJson[category].

Categories

Resources