简体   繁体   中英

Trouble handling nested JSON data

I have a JSON data and i'm having trouble with one nested object. You can see there is two metadata object, my aim is to get image link.

obj.metadata.url

is working, but this isn't work.

obj.metadata.metadata.image 

what am i missing here?

{
  "tokenId": "0",
  "metadata": {
    "url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
    "metadata": {
      "name": "Illuminati #0",
      "image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
      "attributes": [
        {
          "trait_type": "Background",
          "value": "Stained Glass"
        },
        {
          "trait_type": "Frames",
          "value": "Stained Glass"
        }
      ]
    },
    "tokenId": "0"
  }
}

From your question it seems that you are dealing with JSON data instead of JavaScript objects. In order to get the attributes of JSON, you will first need to parse the JSON using JSON.parse() , then you can use . to get the properties you want.

data = {
  "tokenId": "0",
  "metadata": {
     "url": "https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0",
      "metadata": {
      "name": "Illuminati #0",
      "image": "https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png",
      "attributes": [
      {
        "trait_type": "Background",
        "value": "Stained Glass"
      },
      {
        "trait_type": "Frames",
        "value": "Stained Glass"
      }
     ]
  },
  "tokenId": "0"
  }
};

obj = JSON.parse(data);
console.log(obj.metadata.url)
// 'https://gateway.pinata.cloud/ipfs/QmSnTNGbhD/0'
console.log(obj.metadata.metadata.image);
// 'https://gateway.pinata.cloud/ipfs/QmW8pAhkNr/5499.png'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM