如何从JSON中仅解析某些属性和值

时间:2013-09-20 04:05:11

标签: javascript json

我正在尝试解析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:缺少分号。

我有DEMO。我怎样才能只解析"原因"属性/值以及它发生的次数?

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分: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(', ');
    });
});

答案 2 :(得分: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']);
    }
}); 

答案 3 :(得分: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;
}