I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");
Related
I have a json structure as:
{
"TestCaseList": [
{
"TC_1": {
"name":"verifyloginpagedetails",
"value":"2"
},
"TC_2": {
"name":"verify registration page details",
"value":"3"
}
}
],
"Summary": {
"v":[
{
"name":"over the ear headphones - white/purple",
"value":1
}
]
}
}
How to extract the values name, value of TC_1 , TC_2 where TC_1 is dynamic i.e. key of TestCaseList?
You can use the Object.keys method to get an array of the keys of an object.
With a single object in the array at "TestCaseList" in your JSON object, this will work:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
If, however, the array at "TestCaseList" contains more than one one element, you can use this to get each set of keys in an individual array:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
I'm sure a more elegant solution exists, but this will do the trick.
var myObj = {
"TestCaseList":
[{
"TC_1":
{"name":"verifyloginpagedetails",
"value":"2"},
"TC_2":
{"name":"verify registration page details",
"value":"3"}
}],
"Summary":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
}
}
let testCaseListKeys = Object.keys(myObj.TestCaseList[0]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
console.log(tclKey + "\'s name = " + myObj.TestCaseList[0][tclKey].name);
console.log(tclKey + "\'s value = " + myObj.TestCaseList[0][tclKey].value);
}
The console.logs are your output. The important values there are the myObj.TestCaseList[0][tclKey].name and the myObj.TestCaseList[0][tclKey].value
** UPDATE **
After answering the question Ananya asked how to do this same thing if the object had a different structure.
Updated Object:
var myObj2 = {
"TestCaseList":
[{
"TC_1":{
"name":"verifyloginpagedetails",
"value":"2"}
},
{
"TC_2":{
"name":"verify registration page details",
"value":"3" }
}],
"Summary":
{
"v":[ {"name":"over the ear headphones - white/purple","value":1} ]
}
}
Updated JavaScript:
for(x=0;x<myObj2.TestCaseList.length;x++) {
let testCaseListKeys = Object.keys(myObj2.TestCaseList[x]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
//console.log(tclKey);
console.log(tclKey + "\'s name = " + myObj2.TestCaseList[x][tclKey].name);
console.log(tclKey + "\'s value = " + myObj2.TestCaseList[x][tclKey].value);
}
}
I have the following JSON object:
"StudentData": {
"Name": "Mike",
"Age": 25,
"DateOfBirth": 9/25/1993,
"IsMarried": false
}
I'm working on a Javascript function that will present a dialog box to a user with the above information inside of it, however I'd like the information to be preceded with the object's name (i.e. "StudentData").
Let's say I have this object stored within a variable in my function, and let's call it myStudent.
I stumbled upon a post on SE using Object.keys(myStudent)[0] to get property name of the first key within StudentData, but I'm looking to extract the name of the object itself.
How may I go about doing this?
Thank you :)
EDIT:
I'm looking to get StudentData string, not any of the keys contained within the StudentData object itself.
but I'm looking to extract the name of the object itself.
Objects do not themselves have "names". There is some confusion in other answers thinking you are just trying to get the "Name" property inside the object, and not trying to get the value "StudentData". The only way you could do this is if it was stored in an object something like this:
let myObject = {
"StudentData": {
"Age": 25,
"IsMarried": false
}
}
And then you could use the solution you found of Object.keys(myObject)[0] to get "StudentData" but if it is not stored like that there is no standard way of getting that value. Even in the above example, the object containing Age etc does not have a "name" of "StudentData", it is simply associated with the key "StudentData" in the outer object.
Try like this:
var obj = {
"StudentData": {
"Name": "Mike",
"Age": 25,
"DateOfBirth": 9/25/1993,
"IsMarried": false
}
};
// to get the first key
var keys = Object.keys(obj);
console.log(keys[0]);
// or to get the StudentData keys:
var objectKeys = Object.keys(obj.StudentData);
console.log(objectKeys);
// or to populate dinamically a table
let k, tr = '';
for (k in obj.StudentData) {
tr += '<tr><td>' + k + '</td><td>' + obj.StudentData[k] + '<td></tr>';
}
$('table.popup tbody').append(tr);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="popup">
<thead>
<tr>
<td><b>Property</b></td>
<td><b>Value</b></td>
</tr>
</thead>
<tbody></tbody>
</table>
If you stored this object as
var myStudent = { "StudentData": {
"Name": "Mike",
"Age": 25,
"IsMarried": false
}
}
Just do simply myStudent.StudentData.Name to get the value 'Mike'.
And If you really wants to get the key out of object. you can run the below code.
( function getKeyValueFromJSON() {
var myStudent = { "StudentData": {
"Name": "Mike",
"Age": 25,
"IsMarried": false
}
}
for(var val in myStudent.StudentData) {
console.log("Key: " + val + " value: " + myStudent.StudentData[val]);
}
})();
I have made a JSON object and getting so many errors. I am new to JSON so kindly help. Posting here with the screenshots.
Any help would be appreciated.
[![var data\[\]= {"cars":
"Honda":\[
{"model":"Figo" },
{"model":"City"}
\],
"Audi": \[
{"model":"A6"},
{"model":"A8"}
\]
}
data.cars\['Honda'\]\[0\].model
data.cars\['Honda'\]\[1\].model
data.cars\['Audi'\]\[0\].model
ata.cars\['Audi'\]\[1\].model
for (var make in data.cars) {
for (var i = 0; i < data.cars\[make\].length; i++) {
var model = data.cars\[make\]\[i\].model;
alert(make + ', ' + model);
}
}][1]][1]
Using JSONformatter and validator site for checking my code.
Since you mentioned
I am totally novice for JSON
I would like to explain you this completely.
There are little bit of syntax errors in the way you are doing this. You are actually doing a for loop inside a javascript object which will obviously break. If your intention is to alert all the models of all the make, then here is how you do it..
initially you have this
var data = {
cars:{
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
}
You have a variable called data which is a object ({} refers to object) and this object has a property called cars and this property holds a object({} refers to object). Now this object has 2 properties Honda and Audi. Each of this properties are of type array ([] refers to array). And this each array further contains list of objects.
So once you are clear with the above point. Let manipulate the object you have.
Do a forloop to get all the properties of the cars object and when we have hold of each property lets loop its array and then extract the model property value.
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
alert(make + ', ' + model);
}
}
Also dont get confused with Javascript Object and JSON....
In the above example the variable data is Javascript Object and when you do JSON.strinfigy(data) you are converting this Javascript object into string format and that string format is called JSON...
A Demo Fiddle to help you understand better.
Imho it's more like :
var cars = {
"Honda":
[
{"model":"Figo" },
{"model":"City"}
],
"Audi":
[
{"model":"A6"},
{"model":"A8"}
]
}
If you want a huge JSON object storing many cars attributes arrays.
Why do you use these "/" everywhere ?
(PS : if you wanna see some examples -> http://json.org/example.html)
I believe this is the structure your looking for:
cars={
make:{
honda:[
{
model:"accord",
color:"black",
cylinders: "6",
year:"2012"
},
{
model:"civic",
color:"white",
cylinders: "4",
year:"2015"
}
],
acura:[
{
model:"integra",
color:"red",
cylinders: "4",
year:"1992"
},
{
model:"RSX",
color:"Metallic Blue",
cylinders: "4",
year:"2016"
}
],
audi:[
{
model:"R8",
color:"white",
cylinders: "8",
year:"2015"
},
{
model:"A8",
color:"red",
cylinders: "8",
year:"2016"
}
]
}
};
document.addEventListener('DOMContentLoaded',()=>{
var models=[],colors=[],cylinder=[],year=[]; //INSTANTIATE ARRAYS
for(p in cars.make){ //LOOP THROUGH OBJECT PROPS (CARS.MAKE)
cars.make[p].forEach((o)=>{ //LOOP THROUGH (CARS.CARS.PROPS) PUSH OBJ INTO ARRAYS
models.push(o.model);
colors.push(o.color);
cylinders.push(o.cylinders);
year.push(o.year);
});
console.log(models);
console.log(colors);
console.log(cylinders);
console.log(year);
});
I have a json data coming from rest in following format:
{
"status_code": 200,
"data": {
"units": -1,
"unit_reference_ts": null,
"tz_offset": -4,
"unit": "day",
"countries": [{"country": "IN", "clicks": 12}]},
"status_txt": "OK"
}
I want to access the countries part and need to generate data in format like
{"IN":12, ......}
I dont know how to iterate through javascript, JSON array? Please help i am confused between methods which is the best & easiest that will work throughout the JSON?
I tried this:
$.each(response.countries, function(key, value) {
console.log(value.country + ": " + value.clicks);});
but it is showing me type error e is undefined...
Make sure you parse your JSON first (var data = JSON.parse(json)), then use a simple loop:
var obj = {};
for (var i = 0, l = data.data.countries.length; i < l; i++) {
var tmp = data.data.countries[i];
obj[tmp.country] = tmp.clicks
}
console.log(obj); // { IN: 12, UK: 123 }
DEMO
Since (from your edit) you're using jQuery, you'll probably need to do this (note that jQuery automatically parses JSON data if you retrieve it using one of its AJAX methods):
var obj = {};
$.each(response.data.countries, function(key, value) {
obj[value.country] = value.clicks;
});
If you want a string instead of an object, just JSON.stringify the obj:
var json = JSON.stringify(obj);
DEMO
How would you get the value of assocIMG by key matching the key eg
if I have a var 11786 I want it to return media/catalog/product/8795139_633.jpg
var spConfig = {
"attributes": {
"125": {
"id": "125",
"code": "pos_colours",
"label": "Colour",
"options": [{
"id": "236",
"label": "Dazzling Blue",
"price": "0",
"oldPrice": "0",
"products": ["11148"]
}, {
"id": "305",
"label": "Vintage Brown",
"price": "0",
"oldPrice": "0",
"products": ["11786", "11787", "11788", "11789", "11790", "11791", "11792", "11793"]
}]
}
}
};
var assocIMG = // Added - Removed { here, causes issues with other scripts when not working with a configurable product.
{
11786: 'media/catalog/product/8795139_633.jpg',
11787: 'media/catalog/product/8795139_633.jpg',
}
Above is the objects I am working with and below is my current jQuery. Help would be greatly appreciated.
$('#attribute125').change(function() {
var image = $(this).val();
$.each(spConfig.attributes, function() {
prods = $(this.options).filter( function() { return this.id == image; } )[0].products[0];
alert(prods);
});
});
You can use bracket notation to get object members by their keys. You have the variable prods containing a string ("11786"), and the object assocIMG with various keys. Then just use
assocIMG[prods]
to get the property value 'media/catalog/product/8795139_633.jpg' which is associated with that key.
Note that you should always use strings as keys in your object literal, IE does not support numbers there:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg'
};
Another improvement to your script would be not to loop through the spConfig.attributes each time, and potentially execute your action multiple times if an image is contained in more than one attribute. Instead, build a hash object out of it, where you can just look up the respective product id.
var productById = {};
$.each(spConfig.attributes, function() {
$.each(this.options, function() {
var id = this.id;
productsById[i] = this.products[0];
});
});
$('#attribute').change(function() {
var id = this.value;
var prod = productById[id];
var image = assocIMG[prod];
$("#product_img").attr("src", image);
});
You should not use numbers as object keys (in their start). If you want to get the value associated with the 11786 integer key, you will need to use this syntax:
assocIMG["11786"] or assocIMG[11786]
Not
assocIMG.11786
The first thing that you need to do is to create your keys as strings, since you would have:
var assocIMG = {
"11786": 'media/catalog/product/8795139_633.jpg',
"11787": 'media/catalog/product/8795139_633.jpg',
}
But even doing this, you won't be able to access the field using assocIMG.11786 and the first valid sintax that I presented will still work. The correct approach would be:
var assocIMG = {
id11786: 'media/catalog/product/8795139_633.jpg',
id11787: 'media/catalog/product/8795139_633.jpg',
}
Or
var assocIMG = {
"id11786": 'media/catalog/product/8795139_633.jpg',
"id11787": 'media/catalog/product/8795139_633.jpg',
}
Note that the keys are now starting with letters, not numbers. And now, you will can access the 11786 field as assocIMG.id11786 or assocIMG["id11786"], not assocIMG[id11786]
To Get the Value from object by matching key I ended up with the following
$.each(assocIMG, function(index, value) {
if(index == prods) {
var image_path = value;
$("#product_img").attr("src", image_path);
//alert(image_path);
}