【问题标题】:String to non-array json字符串到非数组 json
【发布时间】:2022-01-13 20:03:03
【问题描述】:

我有一个如下所示的字符串:

 {
  "results": [
    {
      "address_components": [
        {
          "long_name": "Ireland",
          "short_name": "Ireland",
          "types": [
            "establishment",
            "natural_feature"
          ]
        }
      ],
      "formatted_address": "Ireland",
      "geometry": {
        "bounds": {
          "northeast": {
            "lat": 55.38294149999999,
            "lng": -5.431909999999999
          },
          "southwest": {
            "lat": 51.4475448,
            "lng": -10.4800237
 

         }
            }],
    "status" : "OK"
   }

我想把它变成一个我可以轻松遍历的 json。然而,当我在这个字符串上调用 JSON.parse() 时,我得到一个很难遍历的 json 数组。我希望能够从东北方向提取 lat 和 lng,而不必遍历整个数组。

【问题讨论】:

  • 转成 JSON 是什么意思?如果它是一个字符串,它已经是一个 JSON。如果你解析它,你会得到一个对象,而不是 JSON。
  • 如果results数组中有多个元素怎么办?如何在不循环的情况下获得所有 lat 和 lng?
  • 数组中有一项。您可以使用[0]。如果有多个项目,无论如何您都会有多个纬度/经度值,因此您需要迭代一些描述。
  • 如果result 键是一个数组,我想不出没有循环的另一种方法
  • object.results[0].geometry.bounds.northeast.lat

标签: javascript arrays json


【解决方案1】:
 var json = `{
    "results": [
        {
            "address_components": [
                {
                    "long_name": "Ireland",
                    "short_name": "Ireland",
                    "types": [
                        "establishment",
                        "natural_feature"
                    ]
                }
            ],
            "formatted_address": "Ireland",
            "geometry": {
                "bounds": {
                    "northeast": {
                        "lat": 55.38294149999999,
                        "lng": -5.431909999999999
                    },
                    "southwest": {
                        "lat": 51.4475448,
                         "lng": -10.4800237
                    }
                }
            }
        }
   ],
   "status" : "OK"
}`;
var data = JSON.parse(json);
var bounds = data.results[0].geometry.bounds;
var bound = bounds.northeast || bounds.southwest;
console.log(bound.lat, bound.lng);

如果您知道东北始终是一个选项,您可以将其简化为:

console.log(data.results[0].geometry.bounds.northeast);

这会给你你的纬度和经度。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多