【问题标题】:How can i get the part that i want only from my Json?我怎样才能从我的 Json 中获得我想要的部分?
【发布时间】:2018-05-28 23:16:57
【问题描述】:

我当前的Json 在下面共享,这是我在node.js 中的request.get 的响应,它在body,我想要的只是json 的一部分,用于进一步处理也共享如下:

{
  "query": "THIS IS MY JSON",
  "topScoringIntent": {
    "intent": "INTENT",
    "score": 0.9796973
  },
  "intents": [
    {
      "intent": "INTENT",
      "score": 0.9796973
    },
    {
      "intent": "None",
      "score": 0.0332397744
    },
    {
      "intent": "ANOTHER INTENT",
      "score": 0.0205348358
    },
    {
      "intent": "YET ANOTHER INTENT",
      "score": 0.0141741727
    },
  ],
  "entities": [
    {
      "entity": "FIRST ENTITY",
      "type": "FIRST TYPE ENTITY",
      "startIndex": 38,
      "endIndex": 47,
      "score": 0.5666461
    },
    {
      "entity": "SECOND ENTITY",
      "type": "SECOND TYPE ENTITY",
      "startIndex": 20,
      "endIndex": 32,
      "resolution": {
        "values": [
          {
            "timex": "2017-12-14T04",
            "type": "datetime",
            "value": "2017-12-14 04:00:00"
          }
        ]
      }
    }
  ]
}

我想提取对象entities

【问题讨论】:

    标签: javascript json node.js parsing


    【解决方案1】:

    您应该首先将 JSON 字符串的主体解析为 Javascript 对象。
    你可以试试下面的代码:

    let json = JSON.parse(body);
    let entities = json.entities
    

    【讨论】:

      【解决方案2】:

      您始终可以使用 HTTP GET 方法:

      function httpGetAsync(jsonPathOrUrl, callback)
      {
          var xmlHttp = new XMLHttpRequest();
          xmlHttp.onreadystatechange = function() { 
              if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
                  callback(xmlHttp.responseText);
          }
          xmlHttp.open("GET", jsonPathOrUrl, true); // true for asynchronous 
          xmlHttp.send(null);
      }
      
       function callback(response){
           if(response.entities) return response.entities;
        }
      

      【讨论】:

        【解决方案3】:

        您只需像浏览任何 JavaScript 对象一样浏览您的 JSON。在文档中,例如:

        {
          "x": "y"
        }
        

        然后您可以使用json.x 访问y 值。在你的情况下,它可能只是:

        json.entities
        

        其中json 是代表您解码的 JSON 值的变量。如果只是字符串,JSON.parse 获取数据。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2020-09-11
          • 2019-12-17
          • 2017-05-25
          • 2011-06-04
          • 2017-09-29
          • 1970-01-01
          • 2012-10-02
          相关资源
          最近更新 更多