3

我有多个具有相同架构的 JSON 文件:

{"q0":{"query":"William","limit":3}}
{"q1":{"query":"Joe","limit":3}}

使用 xpath 或 JSONPath 我想将每个元素提取到一个表中:

|id | query   |limit |
|q0 | William | 3    |
|q1 | Joe     | 3    |

我使用查询和限制字段没有问题..query..limit但我找不到提取id字段的语法(即q0q1)。

我一直在尝试@*$*但没有成功。那么有没有办法选择一个没有节点名的 JSON 元素呢?

正如评论中所说,我正在使用 talend tExtractJSONField 组件,它使用 XPath 来解析 JSON。

4

4 回答 4

2

使用.您可以获得当前元素。不可能使用 JsonPath 来提取键名。因此,您可以在 JavaScript 中通过使用for和获取键名来执行此操作。

以下 HTML 显示了一个完整的示例:

<html>

  <head>
    <link rel="stylesheet" href="style.css">
    <script src="jsonpath.js"></script>    
  </head>

  <body>
    <h1 id="h1"></h1>
    <script type="text/javascript">
      var o = {"q0":{"query":"WilLIAM","limit":3}};
      var key;
      for(var i in jsonPath(o, ".")[0]) key = i;
      document.getElementById("h1").appendChild(document.createTextNode(
        key
        ));
    </script>
  </body>

</html>

这是一个 Plunkr:http ://plnkr.co/edit/CaZD1lVhr1E2S8VN5vnP

于 2014-04-17T08:46:39.147 回答
0

http://goessner.net/articles/JsonPath/上的文档将指向$.q0.

于 2014-04-17T06:47:24.253 回答
0

通过使用 Google 的 Gson 库,您可以阅读如下内容。

HashMap<String, JsonElement> myMap = new Gson().fromJson(jsonString, new TypeToken<HashMap<String, JsonElement>>(){}.getType());

String id = null, query = null;
int limit = 0;

for (Entry<String, JsonElement> entry : myMap.entrySet()) {
  id = entry.getKey();
  if(entry.getValue() != null) {
    JsonElement je = entry.getValue();
    if(je.isJsonObject()) {
      JsonObject jo = je.getAsJsonObject();
      query = jo.get("query").getAsString();
      limit = jo.get("limit").getAsInt();
    }
  }
}
print("id : " + id + " query : " + query + " limit : " + limit);
于 2014-04-24T17:32:02.243 回答
0

实际上,您可以使用 DefiantJS 在您的 JSON 结构上使用 XPath。该库使用“search”方法扩展了全局对象 JSON - 您可以使用 XPath 查询 JSON 结构。该方法将匹配项作为数组返回。

var data = [
       {
          "q0": {
             "query": "William",
             "limit": 3
          }
       },
       {
          "q1": {
             "query": "Joe",
             "limit": 1
          }
       },
       {
          "q1": {
             "query": "Bill",
             "limit": 2
          }
       }
    ],
    found_1 = JSON.search(data, "//*[limit=3]"),
    found_2 = JSON.search(data, "//*[limit>1]");

document.getElementById('output_1').innerHTML = found_1[0].query;
document.getElementById('output_2').innerHTML = found_2[0].length;

要查看此操作,请查看此小提琴;http://jsfiddle.net/hbi99/zWU6x/

此外,请查看此处的 XPath Evaluator 以查看和测试 XPath 查询; http://defiantjs.com/#xpath_evaluator

于 2014-05-18T12:21:05.527 回答