I have a json output array like this
{
"data": [
{
"name": "Ben Thorpe",
"id": "XXXXXXXXXXX"
},
{
"name": "Francis David",
"id": "XXXXXXXXXXX"
},
}
I want to loop through it and print out the all the names using javascript. I want to be able to do this.
for(i=0;i<length;i++){
var result += response.data[i].name + ', ';
}
But I am unable to find the length of the json object using javascript.
response.data is an array of objects, thus has a length property that you can use to iterate its elements.
var result;
for(var i=0;i<response.data.length;i++)
{
result += response.data[i].name + ', ';
}
If you just want to look at it for debugging purposes, do a console.log(myObject) or console.dir(myObject) and take a look at the firebug/chrome/safari console.
The object doesn't automatically have a length property because it's not an array. To iterate over properties of an object, do something like this:
for (var p in location) {
console.log(p + " : " + location[p]);
}
In some cases you may want to iterate over properties of the object, but not properties of the object's prototype. If you're getting unwanted stuff with the regular for..in loop, use Object.prototype's hasOwnProperty:
for (var p in location) if (location.hasOwnProperty(p)) {
console.log(p + " : " + location[p]);
}
The thing is, if this is/was really JSON data, it should have been a string at some point, as JSON is by definition a string representation of an object. So your question "How to print json data" almost reads like "How to print a string." If you want to print it out, you should be able to catch it before it gets to whatever parsed it into that object and just print it out.
Related
I am reading the book "JavaScript for web designers" and I've come to this example:
var fullName = {
"first": "John",
"last": "Smith"
};
for (var name in fullName) {
console.log(name + ": " + fullName[name]);
}
The output is:
"first: John"
"last: Smith"
What I don't get is: where do I tell the program to get the string "first" and "last". I mean, cycling the object "fullName", I fail to see how "name" can be related to "first" and "last". I hope this is clear.
Can you help? Many thanks!
for..in iterates over the keys of an object. You can then access an objects values by name using brackets.
var obj = {
a: 1,
b: 2,
c: 3
};
for (var key in obj) {
console.log('Key:', key);
console.log('obj[key] == obj["' + key + '"] == obj.' + key);
console.log('obj.' + key + ' == ' + obj[key]);
}
It's pretty simple to learn and/or understand. You're looping through all of the properties in the object fullName. For each property, you're giving it the temporary name/alias of name
So you could change it to for (var anything in fullName) and then in the body of the for loop you would reference each property by the name anything like so:
for (var anything in fullName) {
// anything is an alias for the current property your on of the object you're looping through
console.log(anything + ": " + fullName[anything]);
}
A for..in loop will iterate through the object's keys. If you use this on an array, then it (most browser engines) will convert the array into an object behind the scenes (read more on Dictionary Mode) and iterate the keys.
You can view the keys by using
var fullName = {
"first": "John",
"last": "Smith"
};
console.log(Object.keys(fullName));
And essentially the result of this call is then iterated. Keep in mind that using for..in does not guarantee order of the key value pairs.
in the above code name represent key of the object,
first and last are both keys in the object. and can be used to access the value in the object.
like in the first run of the loop it will be something like this
for("first" in fullName) {
console.log("first" + ": " + fullName["first"] //John);
}
When you loop through an object, you iterate through the keys. The keys of this object are first and last. Refer to https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in for more information.
I am retrieving JSON from a live streaming data.
For the first call I am getting dataset array with time and value. But in the second JSON dataset array is empty. I want to check if dataset array contains time key.
Retrieved JSON after first call:
{
"activities-heart-intraday": {
"dataset": [{
"time": "00:00:00",
"value": 91
}, {
"time": "00:01:00",
"value": 92
}, {
"time": "00:02:00",
"value": 92
}],
"datasetInterval": 1,
"datasetType": "second"
}
}
Retrieved JSON after second call:
{
"activities-heart-intraday": {
"dataset": [],
"datasetInterval": 1,
"datasetType": "second"
}
}
I am doing
var value = JSON.parse(data);
if (value.hasOwnProperty('time')) {
console.log("here");
}
to check if time key exists in the JSON, but it's not working.
How can I check if a particular key exists in the array in json?
Firstly you have to check that dataset is not an empty array. Then check that time is defined.
This can be solved with:
if (dataset[0] !== undefined && dataset[0].time !== undefined)
or just:
if (dataset[0] && dataset[0].time)
If you want to iterate through the array:
dataset.forEach(function (data) {
if (data.time) {
// your code
}
});
the data has a dataset array so we need to first check if the array is there and then if one of the arrays members has the time property
if( data.hasOwnProperty('dataset') && data.dataset.length != 0){
if( data.dataset[0].hasOwnProperty('time')){
console.log('true');
}
}
Since in JS you can not natively set and access object properties those with a "-" character in it by dot notation you have define them as strings and use bracket notation instead to set and access them. So you can make a check like this
data["activities-heart-intraday"].dataset.length > 0 && data["activities-heart-intraday"].dataset.every(e => !!e.time);
I can't really tell what data from your question is supposed to be but if it is the whole JSON object, then the most simple way is this:
if(data["activities-heart-intraday"]["dataset"][0]["time"])
console.log('time is set)
But beware! If for example the dataset is not set, you'll get an error that you are trying to get time key from undefined and the code will crash. I'd recommend using simple recursive function like this:
function is_there_the_key(json, keys){
if(keys.length == 0)
return true //we used the whole array, and every key was found
let key = keys.shift() //pop(get and remove) the first string from keys
if(!json[key]){
console.log(key + ' not found')
return false //one of the keys doesn't exist there
}
return is_there_the_key(json[key], keys)
}
Whether you return true or false, both of them will make their way up to the surface.
As the json parameter you pass the json you want to search in.
As the keys parameter you pass an array (mostly strings) of the keys in order they should go.
For example:
if(is_there_the_key(data, ["activities-heart-intraday", "dataset", 0, "time"])
//we found the key, do something here
I have a JSON data from a URL and c am consuming it using jQuery ajax method.
Now as the JSON code below shows I have a DATA array containing objects in my JSON, now if I access FirstName using resp.DATA[0].FirstName, I am able to get it, but now I have to display all the key value pairs in DATA array and i don't know the key name i.e. I have to show every key and value.
There are two customers on data.
How can I do it either using JavaScript or jQuery?
JSON DATA:
{
"ERROR": [],
"DATA": [{
"CustomerID": "124",
"BranchID": "12",
"FirstName": "sandeep",
"LastName": "b",
"EmailID": "gggg#gmail.com",
"Sex": "Male",
"Landline": "",
"AlternateNumber": "",
"Password": "5735c2801",
"USERVARCHAR_2": ""
}],
"META": {
"totalPages": "1",
}
}
I have to display Key and value of each customer data in the form KEY:VALUE, so please suggest me how to loop this.
Use the for loop to iterate over javascript array literal
for (var key in resp.DATA) {
// skip loop if the property is from prototype
if (!resp.DATA.hasOwnProperty(key)) continue;
var objct = resp.DATA[key];
for (var prop in objct) {
// skip loop if the property is from prototype
if(!objct.hasOwnProperty(prop)) continue;
// your code
alert("The key is "+prop + "and the value is " + objct[prop]);
}
}
References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
Use Object.keys(object_name) to fetch all the keys of a Object.
The Object.keys() method returns an array of a given object's own
enumerable properties, in the same order as that provided by a
for...in loop (the difference being that a for-in loop enumerates
properties in the prototype chain as well).
for(var cust of resp.DATA){ // To iterate a array
for(var key in cust){ // To iterate a object ennumerable properties
console.log("Key is: "+key+" and Value is: "+cust[key]);
}
}
do this:
$(resp.DATA[0]).each(function(key, value){
// your code
});
Loop in to your array like this using .each()
$.each(your_array, function(key, value) {
alert('Array Key is: '+ key + ' \n Array Key value is: ' + value);
});
.each() Iterate over a jQuery object, executing a function for
each matched element.
I have a Json data as listed below:
var x = {
"array1":"['x1','x2']",
"array2":"['a1', 'a2']"
}
I need to print the individual elements of the array as below
x1
x2
a1
a2
When I do var y = JSON.parse(x), it gives me "Unexpected token o"
It seems to be coming from the JSON.parse line. If I do x = '["x1", "x2"]', there is no error but I need to have two arrays in the JSON. So how do I read them
Thanks for any answers
That is not JSON. JSON is a string and not an object hence its abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old JavaScript Object. They are different. The former is a data exchange format similar to YAML or XML while the latter is an actual object with properties and values.
Your POJO does have JSON values but since it is already an object you can't use JSON.parse to parse the entire object. That is where the "o" is coming from in the error message. JSON.parse will coerce the first argument to a string if it is not a string:
var foo = {};
JSON.parse(foo); // is essentially doing this foo.toString() which is "[object Object]"
JSON.parse('{}'); // This would parse to an empty object though since it is a string
So now when it attempts to parse "[object Object]" it sees what may be an array but then encounters a character that hasn't been quoted, the "o" in "object", and therefore throws an error.
For your example to be JSON you would need to write it as:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
document.write('<pre>' + JSON.stringify(x, null, 4) + '</pre>');
And so, now that we have a real JSON value we can answer your original question:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
var vals = Object.keys(x).sort().reduce(function (arr, key) {
arr = arr.concat(x[key]);
return arr;
}, []).join('\n');
document.write('<pre>' + vals + '</pre>');
I think your JSON should be like the following
{
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}
Create your array in many different ways - two examples
var x = [{array1:['x1','x2']},{array2:['a1','a2']}]
x[1].array2 produces ["a1", "a2"]
x[1].array2[0] produces "a1"
var xx = {array1:['x1','x2'],array2:['a1','a2']}
xx.array2 produces ["a1", "a2"]
xx.array2[0] produces "a1"
third example
var xxx = {array1:{x1:'x1',x2:'x2'},array2:{a1:'a1',a2:'a2'}}
xxx.array1.x1 produces "x1"
What you have there, that 'x' variable var x = {"array1":[...]...} is already a javascript object, so you can simply pass through the object keys and display the values.
Given 'x' as the object you can have something like:
var key,
result = '';
for (key in x) {
if (x.hasOwnProperty(key)) {
result = result + x[key].join('\n') + '\n';
}
}
// There you have the result...
As John said earlier, for JSON.parse() you wold need a string as a parameter to be able to parse it into a javascript object.
so, you can use this script to do that (correct json too - http://jsonformatter.curiousconcept.com/ -, don't know why this downrate.....i guess a noob didnt realize :D):
var x = {
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}
for (var key in x) {
if (x.hasOwnProperty(key)) {
document.getElementById("test").innerHTML += key + " -> " + x[key]+" <br>";
}
}
i've created a working fiddle here:
https://jsfiddle.net/rjzzqLmr/1/
This question already has answers here:
How do I iterate over a JSON structure? [duplicate]
(13 answers)
Closed 8 years ago.
I would like to iterate through a json object which I got from var jsonObj json_encode( <?php echo $php_array ?>);. This looks to me like a different format to what most people have. For example, w3schools shows this as a json object:
{
"employees": [
{ "firstName":"John" , "lastName":"Doe" },
{ "firstName":"Anna" , "lastName":"Smith" },
{ "firstName":"Peter" , "lastName":"Jones" }
]
}
Mine seems to have completely structure:
{"PINEFOREST JEWELRY":
["3034.25","2002-01-02"],
"AMBERS DESIGN":
["2034.75","2002-01-02"],
"ELEGANT JEWELERS":
["206","2002-01-02"],
"SALEM'S JEWELERS":
["406","2002-01-02"]}
Am I able to iterate through this?
You can use a for loop to iterate through the object's direct properties as follows:
var val;
for(var key in obj) {
if(obj.hasOwnProperty(key)){
val = obj[key];
console.log(val);
}
}
You can use a for in with a nested for
for (var key in data) {
for (var i = 0; i < data[key].length; i++) {
console.log(data[key][i]);
}
}
Yes you can itterate through it as it is valid json.
To start of you need to convert the json into something javascript can itterate over, which you can do with JSON.parse() (MDN). Im assuming that the 'json' you described above is a string of 'json' so:
var jewellery = JSON.parse(myJson); // replace myJson with whatever variable is holding your json
At this point you have an object which you can itterate over. One of the easiest ways to do this would be by using Object.keys() (MDN) and Array.forEach() (MDN) like so:
Object.keys(jewellery).forEach(function (key) {
console.log(key); // would log 'PINEFOREST JEWELRY' the first time
jewellery[key].forEach(function (price) {
console.log(price); // Should log '3034.25' the first time
}
});
Give that a try, otherwise you could still use the other solutions other people have submitted, either or would work. This is how I would do it though!!