How to iterate through nested array of JSON in jQuery? - javascript

I have a data in json format getting from PHP script the data is coming in following format as follows:
[{
"type":"checkbox",
"grid-name":"Sports",
"values":["Cricket","Football"],
"input":[{"Cricket":2},{"Football":1}]
},
{"type":"checkbox",
"grid-name":"Hobbies",
"values":["Playing Chess","Swimming"],
"input":[{"Playing Chess":1},{"Swimming":2}]
},
{"type":"radiobutton",
"grid-name":"Gender",
"values":["Male","Female"],
"input":[{"Male":3},{"Female":0}]
},
{"type":"radiobutton",
"grid-name":"Citizen",
"values":["Indian","NRI"],
"input":[{"Indian":3},{"NRI":0}]
},
{"type":"number",
"grid-name":"Age",
"input":["24","23","23"]
},
{"type":"select",
"grid-name":"City",
"values":["Satara","New york","Korea"],
"input":[{"Satara":1},{"New york":1},{"Korea":1}]
}]
i want to capture the values & input array. How to access through nested array?

jQuery:
$.each(yourObject, function( index, value ) {
console.log(value.values);
console.log(value.input);
});
Native js (but better don't use it, accordingly to this):
for (index in yourObject) {
console.log(yourObject[index].values);
console.log(yourObject[index].input);
}
Native js, another example:
for (var i = 0; i < yourObject.length; i++) {
console.log(yourObject[i].values);
console.log(yourObject[i].input);
}

You're looking for $.each. This will allow you to loop through object-arrays.
https://api.jquery.com/jquery.each/
If you're also asking how to capture the values and you have the raw text, you're also looking for $.parseJSON
https://api.jquery.com/jquery.parsejson/

Related

jQuery getJSON print array where name is string

I have some good practice with using php and mysql, and am now starting with JSON.
I've made a simple json index containing paths to folders, and items inside them:
{ "foldery" : [
{
"foName": "website/img/bg",
"files" : [
"website/img/bg/bg1.jpeg",
"website/img/bg/bg2.jpg",
"website/img/bg/bg3.jpg",
"website/img/bg/bg4.jpeg"
]
},
{
"foName": "website/img/post1",
"files" : [
"website/img/post1/a.jpeg",
"website/img/post1/b.jpg",
"website/img/post1/c.jpeg",
"website/img/post1/d.jpg"
]
}
]
}
Now here is my jquery, for now returning a big mess of data, somewhere including the info about the contents inside:
$.getJSON("nameindex.json", function(data) {
console.log(data);
});
What I would like it to do, in mySql looks like this:
SELECT files FROM foldery WHERE foName = "website/img/post1"
Thus the result, would be an array containing all the files inside post1.
Unfortunately tho, after 2 hours of attempts I have nothing more than the simple console.log code.
Any help would be gladly appreciated
You need to iterate over your array and check forName to equality
function select(o, foName) {
var length = o.foldery.length;
for(var i = 0; i < length; i++){
if (o.foldery[i].foName == foName) {
return o.foldery[i].files;
}
}
}
var result = select(o, "website/img/post1")
console.log(result);
Result
[ 'website/img/post1/a.jpeg',
'website/img/post1/b.jpg',
'website/img/post1/c.jpeg',
'website/img/post1/d.jpg' ]

Verify all columns of the array for a determined pattern

I have the following javascript code
var list = [
{
Date : '2014-12-31 12:23:43',
DateStart: '1980-12-30 23:43:42',
Name: 'Kate',
...
...
},
{
Date : '1978-05-21 23:43:65',
DateStart: '1973-04-06 12:34:09',
Name: 'John',
...
...
}
];
And the following code to verify for regex pattern:
for (var i in list) {
var data = [];
if (/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/.test(list[i].?)) {
data.push({Data: list[i].Data });
}
}
The variable i from the above code is to interact with each line of the array.
How can I interact through for loops with each line and column without having to specify this in the question mark from the above code?
What can I do to all columns be verified for the date pattern?
Making the array date stay only with the values
2014-12-31 12:23:43,
1980-12-30 23:43:42,
1978-05-21 23:43:65,
1973-04-06 12:34:09
How can I interact through for loops with each line and column without having to specify this in the question mark from the above code?
You have to specify the field you want to access, how else should the interpreter be able to know what you want to access?
If you want to avoid using an indexer you can use external libraries like underscore.js to iterate over the collection:
http://underscorejs.org/#each
_.each(list, function(item) {
// validate item.Date and item.DateStart here
});
Alternatively there is a very concise post about this topic here: For-each over an array in JavaScript?
Was this what I wanted
for (var j = 0; j < list.length; j++) {
for (p in list[j]) {
if (/(\d{4})-(\d{2})-(\d{2}) (\d{2}):(\d{2}):(\d{2})/.test(list[j][p])) {
data.push({Data: list[j][p] });
}
}
}

Searching json array for a specific attribute

Actually I want to search an attribute's value in an json array for one of its child. Now one condition is that the attribute will not be there in all the child's of the array. This is my json array.
[{
"heading1":"heading1",
"heading2":"heading2",
"heading3":"heading3",
"heading4":"heading4",
"heading5":"heading5",
"heading6":"heading6"
},
{
"column1":65536,
"column2":"school",
"column3":"testing purpose",
"column4":"DESKTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1":98305,
"column2":"Nikhil",
"column3":"Test",
"column4":"LAPTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}]
So presently I am working with the each loop but like this
var obj = $.parseJSON(JSON.stringify(response));
$.each(obj, function () {
console.log("heading1", this['heading1']);
});
Here response comes from mserver and it is the json array
Now I want to know can I search for this attribute in the json array without using a loop in jQuery.
Based on your sample code what I understand you have is an array of objects and you want to find objects with one specific property and or value:
This will return true if the object has the property
var results= arr.filter(function(item){ return item.hasOwnProperty("column5"); });
Or you can perform additional action when you find the property:
arr.filter(function(item){
if (item.hasOwnProperty("column5")) {
return item["column5"] === 'demo 01'; //or item.column5 === 'demo 01'
}
return false;
});
This only works on IE9+ if you need this to run in older versions of IE, please follow the instructions under polyfill:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The you can check like
var obj = $.parseJSON(response);
$.each(obj, function (index,value) {
if(typeof obj[index].heading2 !== "undefined")
{
alert(obj[index].heading2);
}
when in other object of array element not find then it returns undefined. and you can check like that.
you can check in this http://jsfiddle.net/gKRCH/
It's best to use a loop. But if the format of the JSON is regular, you could regex for the value in the response string.
I'm not recommending this method, just pointing out that it exists.
var value = "heading1";
if( (new RegExp('"' + value + '"')).test(response) ){
// Found value
};
Here, we take the required value, wrap it in quotation marks and search for it in the response.
This has several issues, such as:
It might find the pattern in a property name
If the value could contain regex special characters, they'll need escaping.
If your JSON contains values with escaped quotation marks, you could get a false positive from partial matches.
That's why it depends on you knowing the format of the data.
EDIT:
You can solve issue 2 by using this condition instead of regex. But it gives you less flexibility.
response.indexOf('"' + value + '"') !== -1
Try this,
$.each(object,function(key, value){
console.log(key);
console.log(value);
});
You can use this JS lib; DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which, you can perform XPath queries on JSON structures. Like the one you have exemplified.
With XPath expressions (which is standardised query language), you can find whatever you're looking for and DefiantJS will do the heavy-lifting for you - allowing your code to be neat and clean.
Here is the fiddle of this code:
http://jsfiddle.net/hbi99/q8xst/
Here is the code:
var data = [
{
"heading1": "heading1",
"heading2": "heading2",
"heading3": "heading3",
"heading4": "heading4",
"heading5": "heading5",
"heading6": "heading6"
},
{
"column1": 65536,
"column2": "school",
"column3": "testing purpose",
"column4": "DESKTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1": 98305,
"column2": "Nikhil",
"column3": "Test",
"column4": "LAPTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}
],
res = JSON.search( data, '//*[column4="DESKTOP"]' );
console.log( res[0].column2 );
// school

Get json data from a file

I wan't to get data from a json file without knowing exacly where the data is:
I have this json
var names= [
{
"category":"category1" ,
"name1":"david",
"name2":"jhon",
"name3":"peter"
},
{
"category":"category2" ,
"name1":"Smith" ,
"name2":"Anna",
}
]
suppose i have a string variable:
var str='category2';
how can i get category2.name1 using the variable?
I don't want to use names[1].name1 because i don't know whats in str and i want to avoid using for loop.
There are some build-in functions that may help you. For example:
var matchingElements = names.filter(function(object, index, array) {
return object.category == str;
});
What you're looking for will always be in matchingElements[0].name1 if matchingElements.length > 0.

Number of items in a json array

Looking for a simple bit of JS to count the number of items in a .json file (each item represents, in this case, an instagram photo being pulled into the web app; I want to count the number of photos). Json is structured thusly...
{
"type":"FeatureCollection",
"features":[
{
"type":"Feature",
"geometry":{
"coordinates":[
-79.40916,
43.87767
],
"type":"Point"
},
"properties":{
"longitude":-79.40916,
"latitude":43.87767,
"title":"",
"user":"cmay2400",
"id":"176051485697457528_13947894",
"image":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_7.jpg",
"images":{
"low_resolution":{
"url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_6.jpg",
"width":306,
"height":306
},
"thumbnail":{
"url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_5.jpg",
"width":150,
"height":150
},
"standard_resolution":{
"url":"http:\/\/distilleryimage0.instagram.com\/1d725a3a8d7511e181bd12313817987b_7.jpg",
"width":612,
"height":612
}
},
"description":"Today's ride <span class=\"tag\">#zipcar<\/span>",
"instagram_id":"13947894",
"likes":1,
"profile_picture":"http:\/\/images.instagram.com\/profiles\/profile_13947894_75sq_1322267355.jpg"
}
},
{
"type":"Feature", [...]
I just want to loop through the json file and count the number of items. Completely lost on where to begin.
Parse the JSON string into an object and use it as you would any other object in JavaScript:
var o = JSON.parse(jsonstring);
alert(o.features.length); /* number of items in features array */
This is more or less the code you are looking for:
var variable = jQuery.parseJSON( stringThatIsStoringJson );
for(var i=0;i<variable.features.length;i++) {
doStuff(variable.features[i]);
for(var j=0;j<variable.features[i].geometry.coordinates.length;j++) {
doMoreStuff(variable.features[i].geometry.coordinates[j]);
}
}
Assuming you are using jQuery. You can parse the JSON with whatever library you want. Just avoid eval(), which opens your site to XSS vulnerabilities.
Of course, the first thing you must transform the json string into js object. by use JSON.parse()(IE6\7 not support) or include the Crockford's JSON2 parser in order to support it on IE < 8.
var obj = JSON.parse(jsonstr);
// loop the obj to find out what you want
Or another way, you can try to use some lib like jsonSelect (CSS-like selectors for JSON.) or something like JSONPath, then you can easy to manipulate your data like:
var reslut = JSONSelect.match('css selector', obj);

Categories