4

我正在尝试解析 JSON。下面的例子,

[
{
    "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."
  }
] 

我只需要打印如下内容:

  • 原因 1:期望一个赋值或函数调用,而是看到一个表达式。
  • 原因 2:缺少分号。

我有一个演示。我怎样才能只解析“原因”属性/值以及它发生了多少次?

4

4 回答 4

1

只需遍历数组对象并搜索您需要的值:

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']);
    }
}); 
于 2013-09-20T04:27:15.883 回答
1
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);
于 2013-09-20T04:10:09.287 回答
1

如果你想打印错误试试这个:

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(', ');
    });
});
于 2013-09-20T04:23:24.047 回答
0

你可以通过这种方式...

第 1 步:将 json 转换为数组。

var tags = $.parseJSON(json_string);

第2步:删除所有'raw'错误字符串数组并打印它们

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;
}
于 2013-09-20T04:25:15.147 回答