简体   繁体   English

嵌套 JSON 数据的故障处理

[英]Trouble handling nested JSON data

I have a JSON data and i'm having trouble with one nested object.我有一个 JSON 数据,我在使用一个嵌套的 object 时遇到问题。 You can see there is two metadata object, my aim is to get image link.可以看到有两个元数据 object,我的目的是获取图片链接。

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.从您的问题来看,您似乎正在处理 JSON 数据而不是 JavaScript 对象。 In order to get the attributes of JSON, you will first need to parse the JSON using JSON.parse() , then you can use .为了获得 JSON 的属性,您首先需要使用JSON.parse()解析JSON ,然后您可以使用 .parse() . 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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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