首页 > 解决方案 > react-native Json copy array url

问题描述

I`m trying copy the types[] by json url.

my url open this:

{
  "html_attributions": [],
  "results": [
    {
      "geometry": {
        "location": {
          "lat": -27.00170259999999,
          "lng": -48.62017489999999
        },
        "viewport": {
          "northeast": {
            "lat": -27.00031801970849,
            "lng": -48.6187919197085
          },
          "southwest": {
            "lat": -27.0030159802915,
            "lng": -48.6214898802915
          }
        }
      },
      "icon": "https://maps.gstatic.com/mapfiles/place_api/icons/restaurant-71.png",
      "id": "96213cc395d0c8ccaa3176875ec8aa2b89f852f8",
      "name": "Dois Amores Comida Árabe",
      "place_id": "ChIJ_RggImq22JQRqQgcG98nfn4",
      "plus_code": {
        "compound_code": "X9XH+8W Balneário Camboriú, SC, Brasil",
        "global_code": "584HX9XH+8W"
      },
      "reference": "ChIJ_RggImq22JQRqQgcG98nfn4",
      "scope": "GOOGLE",
=---> "types": [
        "restaurant",
        "food",
        "point_of_interest",
        "establishment"
      ],
      "vicinity": "Avenida Atlântica, 4054 - Centro, Balneário Camboriú"
    }
  ],
  "status": "OK"
}

I want to return the types [] list to a list so I know what type the place fits into. I didn't find it any way, something closer I got was that.

and my code:

const url = 'myurlgoogleapi';
fetch(url, {
    method: 'POST',
    headers: {
      Accept: 'application/json',

      'Content-Type': 'application/json',
    },
    body: JSON.stringify({

      "html_attributions": [],
      "results": [{
        "types" ["name"]
      }]

    }),
  }).then((response) => response.json())
  .then((responseJson) => {
    console.log(responseJson[0].name);
  })
  .catch((error) => {
    console.error(error);
  });

I`m using console.log just to check if will work, but just error. i need specific the type[] to return your values.

标签: javascriptjsonreact-nativeurl

解决方案


I found a solution:

return fetch(url)
            .then((response) => response.json())
            .then((responseJson) => {
                const tipe = (responseJson.results[0].types[0] + " " + responseJson.results[0].types[1] + " " + responseJson.results[0].types[2]);
                this.setState({ tipe });
            })
            .catch((error) => {
                console.error(error);
            });

Firstly I just needed declare the results[] array and then declare the types[] = responseJson.results[0].types[0]


推荐阅读