Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON using JQuery

I have a JSON as follows

{
  columns      : [RULE_ID,COUNTRY_CODE],
  RULE_ID      : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30], 
  COUNTRY_CODE : [US,US,CA,US,FR,GB,GB,UM,AF,AF,AL,CA,US,US,US]
}

I need to retrive the column names from the columns entry and then use it to search the rest of the entries using jquery. For example I get each column using

jQuery.each(data.columns, function(i,column))

I need to loop throgh the rest of the entries using the values I get from the previous loop. ie without hardcoding COUNTRY_CODE or RULE_ID. What is the best way to do that using Jquery?

like image 306
sarego Avatar asked Dec 09 '08 11:12

sarego


People also ask

How can you parse JSON via jQuery?

The jQuery parseJSON() method takes a JSON string and returns a JavaScript object. The specified JSON string must follow the strict JSON format. Passing an incorrect string will cause a JS exception. As similar to the above strings, multiple other malformed strings will cause an exception.

What does JSON parse () method do when we initiate an Ajax request?

Description: Takes a well-formed JSON string and returns the resulting JavaScript value.

What is JSON parsing?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON.

How can I convert JSON to string?

Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.


2 Answers

jQuery.each(data.columns, function(i,column) {
    jQuery.each(data[column], function(i, row) {
    ....
    });
});
like image 116
Paolo Bergantino Avatar answered Oct 05 '22 15:10

Paolo Bergantino


Some comments:

Paolo is right, you can use data[column] to get the list of values:

jQuery.each(data.columns, function(iCol,column) {
    jQuery.each(data[column], function(iRow, row) {
    ....
    });
});

Do you need the columns information ? You could get the list of "columns" by iterating directly over data:

for( var column in data )
{
    jQuery.each(data[column], function(i, row) {
    ....
    });
}

Not really a question but your JSON is not valid JSON, I hope this was only an example and not your real data:

{
  "columns"      : ["RULE_ID","COUNTRY_CODE"],
  "RULE_ID"      : [1,2,3,7,9,101,102,103,104,105,106,4,5,100,30], 
  "COUNTRY_CODE" : ["US","US","CA","US","FR","GB","GB","UM","AF","AF","AL","CA","US","US","US"]
}
like image 32
Vincent Robert Avatar answered Oct 05 '22 13:10

Vincent Robert