How to parse only specific properties and values ​​from JSON

I am trying to parse JSON. Example below

[ { "id": "(error)", "raw": "Expected an assignment or function call and instead saw an expression.", "code": "W030", "evidence": "v", "line": 1, "character": 1, "scope": "(main)", "reason": "Expected an assignment or function call and instead saw an expression." }, { "id": "(error)", "raw": "Missing semicolon.", "code": "W033", "evidence": "v", "line": 1, "character": 2, "scope": "(main)", "reason": "Missing semicolon." } ] 

I just need to print something like the following:

  • Reason 1: A function assignment or call was expected, and an expression instead.
  • Reason 2: The semicolon is missing.

I have a DEMO . How can I just analyze only the properties / values ​​of the β€œcause” and how many times does this happen?

+4
source share
4 answers

if you want to print errors, try the following:

Javascript

 $(document).ready(function(){ $("#js").keyup(function(){ jsSource = $("#js").val(); JSHINT(jsSource); result = JSON.stringify(JSHINT.errors, null, 2); //storage for reasons var errors = []; for(var i = 0; i < JSHINT.errors.length; i++){ //reason collecting errors.push((i + 1) + ') ' + JSHINT.errors[i].reason); } //print reasons document.getElementById('output').innerHTML = errors.join(', '); }); }); 
+1
source
 var obj = [ { "id": "(error)", "raw": "Expected an assignment or function call and instead saw an expression.", "code": "W030", "evidence": "v", "line": 1, "character": 1, "scope": "(main)", "reason": "Expected an assignment or function call and instead saw an expression." }, { "id": "(error)", "raw": "Missing semicolon.", "code": "W033", "evidence": "v", "line": 1, "character": 2, "scope": "(main)", "reason": "Missing semicolon." } ] ; alert(obj[0].reason); alert(obj[1].reason); 
+1
source

Just skip the array object and find the values ​​you need:

 var obj = [ { "id": "(error)", "raw": "Expected an assignment or function call and instead saw an expression.", "code": "W030", "evidence": "v", "line": 1, "character": 1, "scope": "(main)", "reason": "Expected an assignment or function call and instead saw an expression." }, { "id": "(error)", "raw": "Missing semicolon.", "code": "W033", "evidence": "v", "line": 1, "character": 2, "scope": "(main)", "reason": "Missing semicolon." } ] ; $.each(obj, function(key, value){ if (value && value.hasOwnProperty('reason')){ console.log(value['reason']); } }); 
+1
source

you can do it this way ...

step 1: convert json to array.

 var tags = $.parseJSON(json_string); 

Step 2: delete all the 'raw' in an array of error strings and print them

 var errors= new Array(); var error_no = 1; for (var i = 0; i < tags.length; i++) { var element = tags [i]; var e_String = 'Reason '+error_no; error_no++; error.e_String = element.raw; } 
0
source

All Articles