如何访问JSON中的特定对象

时间:2019-01-07 15:35:34

标签: javascript json

API返回的JSON如下所示:

{
   "html_attributions" : [],
   "result" : {
      "address_components" : [
         {
            "long_name" : "1-3",
            "short_name" : "1-3",
            "types" : [ "street_number" ]
         },
         {
            "long_name" : "Acacia",
            "short_name" : "Acacia",
            "types" : [ "route" ]
         },
         {
            "long_name" : "Alamos 2da Sección",
            "short_name" : "Alamos 2da Secc",
            "types" : [ "sublocality_level_1", "sublocality", "political" ]
         },
         {
            "long_name" : "Santiago de Querétaro",
            "short_name" : "Santiago de Querétaro",
            "types" : [ "locality", "political" ]
         },
         {
            "long_name" : "Querétaro",
            "short_name" : "Qro.",
            "types" : [ "administrative_area_level_1", "political" ]
         },
         {
            "long_name" : "Mexico",
            "short_name" : "MX",
            "types" : [ "country", "political" ]
         },
         {
            "long_name" : "76160",
            "short_name" : "76160",
            "types" : [ "postal_code" ]
         }
      ]
   },
   "status" : "OK"
}

我很想访问“ sublocality”对象并读取其值,在这种情况下为“ alamos 2da secc”。我知道必须先使用JSON.parse解析JSON,但不确定如何访问特定对象。是否需要for循环?还是有一种方法可以使每个对象的类型字段匹配为“ sublocality”

感谢您的协助。

4 个答案:

答案 0 :(得分:2)

如果子地区可能有多个地址,我会采用这种方法:

const response = JSON.parse(apiResponse)
const addressesWithSublocality = response['result']['address_components'].filter(address=>{
    return address['types'].includes('sublocality')
})
console.log(addressesWithSublocality.map(address=>address['short_name']))

.filter函数接受一个数组并将其修剪为仅返回“ true”的项目-在这种情况下,其types包括"sublocality"的地址。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter

.map函数返回一个新数组,这是在原始数组中的每个项目上运行提供的函数的结果-在这种情况下,返回每个地址的short_name

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

如果只有一个地址是亚地区,我会采用这种方法:

const response = JSON.parse(apiResponse)
const addressWithSublocality = response['result']['address_components'].find(address=>{
    return address['types'].includes('sublocality')
})
console.log(address['short_name'])

.find.filter的相似之处在于,它根据要返回“ true”的项修剪数组,但是.find仅返回一项,而.filter总是返回返回一个数组。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

注意:除了使用方括号符号外,您还可以使用点符号,例如您可以写response['result']['address_components']来代替response.result.address_components。在访问JSON时,我只喜欢前一种语法。

答案 1 :(得分:0)

使用数组find()查找所需的对象。

var data = `{"html_attributions":[],"result":{"address_components":[{"long_name":"1-3","short_name":"1-3","types":["street_number"]},{"long_name":"Acacia","short_name":"Acacia","types":["route"]},{"long_name":"Alamos 2da Sección","short_name":"Alamos 2da Secc","types":["sublocality_level_1","sublocality","political"]},{"long_name":"Santiago de Querétaro","short_name":"Santiago de Querétaro","types":["locality","political"]},{"long_name":"Querétaro","short_name":"Qro.","types":["administrative_area_level_1","political"]},{"long_name":"Mexico","short_name":"MX","types":["country","political"]},{"long_name":"76160","short_name":"76160","types":["postal_code"]}]},"status":"OK"}`

data = JSON.parse(data)

var res = data['result']['address_components'].find((e) => {return e.types.indexOf('sublocality') !== -1})

console.log(res['short_name'])

答案 2 :(得分:0)

使用Array#filter查找与作为参数传递的类型匹配的所有名称。

可能有多个匹配项。

const data ={"html_attributions":[],"result":{"address_components":[{"long_name":"1-3","short_name":"1-3","types":["street_number"]},{"long_name":"Acacia","short_name":"Acacia","types":["route"]},{"long_name":"Alamos 2da Sección","short_name":"Alamos 2da Secc","types":["sublocality_level_1","sublocality","political"]},{"long_name":"Santiago de Querétaro","short_name":"Santiago de Querétaro","types":["locality","political"]},{"long_name":"Querétaro","short_name":"Qro.","types":["administrative_area_level_1","political"]},{"long_name":"Mexico","short_name":"MX","types":["country","political"]},{"long_name":"76160","short_name":"76160","types":["postal_code"]}]},"status":"OK"};

function findMatches(type){
  return data.result.address_components
  .filter(({types})=>types.includes(type))
  .map(({short_name})=>short_name)
  .join(", ");
}

const res = findMatches("sublocality");

console.log(res);

答案 3 :(得分:0)

您还可以使用Lodash中的_find查找对象

const response = {
   "html_attributions" : [],
   "result" : {
      "address_components" : [
         {
            "long_name" : "1-3",
            "short_name" : "1-3",
            "types" : [ "street_number" ]
         },
         {
            "long_name" : "Acacia",
            "short_name" : "Acacia",
            "types" : [ "route" ]
         },
         {
            "long_name" : "Alamos 2da Sección",
            "short_name" : "Alamos 2da Secc",
            "types" : [ "sublocality_level_1", "sublocality", "political" ]
         },
         {
            "long_name" : "Santiago de Querétaro",
            "short_name" : "Santiago de Querétaro",
            "types" : [ "locality", "political" ]
         },
         {
            "long_name" : "Querétaro",
            "short_name" : "Qro.",
            "types" : [ "administrative_area_level_1", "political" ]
         },
         {
            "long_name" : "Mexico",
            "short_name" : "MX",
            "types" : [ "country", "political" ]
         },
         {
            "long_name" : "76160",
            "short_name" : "76160",
            "types" : [ "postal_code" ]
         }
      ]
   },
   "status" : "OK"
}

const addressWithSub = _.find(response.result.address_components , (e) => {return e.types.includes('sublocality')})

console.log(addressWithSub.long_name)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.core.js"></script>