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

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

Related

How to retrieve data from json data

[{"id":7,"message":"This is another test message","taker_id":"131","giver_id":"102","status":"0","stamp":"2016-08-11"}]
That's my response. I try to get a datum. I have tried data.id but it fails and returns undefined.
As I assume that you are working with a JSON string, you first have to parse the string into and JSON object. Else you couldn't reach any of the properties.
parsedData = JSON.parse(data);
Then you can get your property:
parsedData[0].id
This seems to work just fine
var data = [{
"id":7,
"message":"This is another test message",
"taker_id":"131",
"giver_id":"102",
"status":"0",
"stamp":"2016-08-11"
}];
console.log(data[0].id);
https://jsbin.com/jewatakize/
if you just want to get the id from this one object then data[0].id will work just fine.
If you expect to have multiple objects in that same array then you can use a loop.
for example if this is angular you can do:
<div ng-repeat='info in data'>
<p>{{info.id}}</p>
</div>
This will allow you to iterate through multiple objects within the array and get all id's.
The problem here is that you have here an array of objects, and you are trying to access it without indexing.
You should first parse it using and then access the object by indexing
let objects = JSON.parse(data)
console.log(objects[0].id)

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/

checking json value in javascript

var saurabhjson= JSON.stringify(data)
above returns this json
saurabhjson {"recordId":5555,"Key":"5656"}
if print the first array in console it get undefined value
console.log("saurabhjson[0].recordId",saurabhjson[0].recordId);
i want to do some check like this
if(saurabhjson[0].recordId == 5555) {
$('#div_ajaxResponse2').text("another success");
}
As the method suggests JSON.stringify(data). It converts a js object to a jsonstring now if you want a key out of this string it can't be done before parsing it to json.
So i don't get it why do you need to stringify it.
And another thing is you have a js object not an array of objects. so you need to use this on data itself:
console.log("data.recordId",data.recordId);
You are probably mixing a few things there.
When you do var saurabhjson= JSON.stringify(data), that saurabhjson variable is a string, not an object, so you can't access its elements like you are trying to do.
Try accessing data directly instead, without using JSON.stringify():
console.log("data.recordId",data.recordId);

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

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