【问题标题】:Parse values from the JSON returned by URL of Google Place API从 Google Place API 的 URL 返回的 JSON 中解析值
【发布时间】:2019-01-02 05:18:44
【问题描述】:

我正在使用 dialogflow-fulfillment 创建一个机器人,并且我正在使用 Google Place API 来提取有关医院的其他信息。

我做了一个虚拟响应,例如,由 Google Place API 返回,这里是链接:http://www.mocky.io/v2/5c2b9f9e3000007000abafe3

{
   "candidates" : [
      {
         "formatted_address" : "140 George St, The Rocks NSW 2000, Australia",
         "name" : "Museum of Contemporary Art Australia",
         "photos" : [
            {
               "height" : 3492,
           "html_attributions" : [
              "\u003ca href=\"https://maps.google.com/maps/contrib/105784220914426417603/photos\"\u003eKeith Chung\u003c/a\u003e"
           ],
           "photo_reference" : "CmRaAAAAaGaCX-kivNEaJ-z97AduTYgW3d98uv53-8skNrS1k1GTgOtiQ1-Z2gfWJydrpkrshuV_kHPKizl088dezEJgIxYGoTWqtJgah-u_I46qNNYMfUbk8LKBZqxzkHyIL1nWEhBO6lPa0NgvlyLGBrXpXFPUGhT0lAUj_oCiOWV2MEYdBeKf-kTtgg",
           "width" : 4656
            }
         ]
      }
   ],
   "status" : "OK"
}

我需要从 Google Place API 返回的 JSON 中解析我选择的值。例如,如果我必须使用 Python 从上面的 JSON 中解析 'name' 的值,我会这样做:

import requests, json
api_key = ''
r = requests.get('https://maps.googleapis.com/maps/api/place/findplacefromtext/json?input=Museum%20of%20Contemporary%20Art%20Australia&inputtype=textquery&fields=photos,formatted_address,name&key=' + api_key)
x = r.json()
y = x['candidates']
print(y[0]['name'])

上面的工作代码清晰且运行良好。考虑到我在Nodejs方面的经验不足,请您告诉我在Nodejs中类似的东西来解析值,例如'name'的值?

您的宝贵回复会鼓励我。

P.S:谦虚地说,问题涉及首先调用 Google Place API,然后从返回的 JSON 中解析值。请按照上面 Python 代码中给出的步骤进行操作,以便更好地理解。

【问题讨论】:

    标签: node.js dialogflow-es google-api-nodejs-client dialogflow-es-fulfillment


    【解决方案1】:

    在异步 HTTP 请求中获取 API 响应(有大量 npm 库,如 request 可帮助您自动设置标头等),然后使用标准库 JSON.parse(body) 获取包含结构化表示的纯 JavaScript 对象API 响应。

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 2017-07-07
      • 2017-09-07
      • 1970-01-01
      相关资源
      最近更新 更多