【问题标题】:JSONPath pattern - keeping object structureJSONPath 模式 - 保持对象结构
【发布时间】:2013-10-16 09:16:33
【问题描述】:

我在使用 JSONPath 做某事时遇到了一些麻烦。这就是我所拥有的:

[
    {
        "id": {
            "type": "literal",
            "value": "123456789",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        },
        "name": {
            "type": "literal",
            "value": "John Doe",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        }
    },
    {
        "id": {
            "type": "literal",
            "value": "2123456789",
            "datatype": "http://www.w3.org/2001/XMLSchema#string"
        },
        "name": {
             "type": "literal",
             "value": "Jane Doe",
             "datatype": "http://www.w3.org/2001/XMLSchema#string"
    }
}

] } ]

应用模式后我想得到的是:

[
    {
        "id": "123456789",
        "name": "John Doe"

     },
     {
        "id": "2123456789",
        "name": "Jane Doe"

     }
]

这可能吗?我正在做的最好的是["123456789", "John Doe","2123456789","Jane Doe"]

图案应该是什么样子的?

【问题讨论】:

    标签: json parsing jsonpath


    【解决方案1】:

    使用 DefiantJS (http://defianjs.com),您可以使用 XPath 表达式查询 JSON 结构。 DefiantJS 使用“搜索”方法扩展了全局对象 JSON,并将匹配项作为类似数组的对象返回。

    这是一个示例代码;

    var data = [
           {
              "id": {
                 "type": "literal",
                 "value": "123456789",
                 "datatype": "http://www.w3.org/2001/XMLSchema#string"
              },
              "name": {
                 "type": "literal",
                 "value": "John Doe",
                 "datatype": "http://www.w3.org/2001/XMLSchema#string"
              }
           },
           {
              "id": {
                 "type": "literal",
                 "value": "2123456789",
                 "datatype": "http://www.w3.org/2001/XMLSchema#string"
              },
              "name": {
                 "type": "literal",
                 "value": "Jane Doe",
                 "datatype": "http://www.w3.org/2001/XMLSchema#string"
              }
           }
        ],
        found = JSON.search(data, '//value'),
        str = '';
    
    for (var i=0; i<found.length; i++) {
        str += found[i] +'<br/>';
    }
    
    document.getElementById('output').innerHTML = str;
    

    要查看此代码的运行情况,请查看此小提琴; http://jsfiddle.net/hbi99/4BZMm/

    有关更多有用的 XPath 表达式,请在此处查看 like XPath Evaluator; http://defiantjs.com/#xpath_evaluator

    【讨论】:

      猜你喜欢
      • 2018-02-11
      • 2020-07-07
      • 2022-08-03
      • 2021-08-30
      • 2011-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多