Home > front end >  Get specific value from json object
Get specific value from json object

Time:02-13

I have a json file with the following structure:

"edition": 979,
  "attributes": [
    {
      "trait_type": "Background",
      "value": "Gray"
    },
    {
      "trait_type": "Base",
      "value": "Guy"
    },
    {
      "trait_type": "Body",
      "value": "FormalBlack"
    },
    {
      "trait_type": "Hand",
      "value": "None"
    },
    {
      "trait_type": "Head",
      "value": "Astronaut"
    },
    {
      "trait_type": "Pet",
      "value": "OrangeCat"
    }
  ],
  "properties": {
    "files": [
      {
        "uri": "979.png",
        "type": "image/png"
      }
    ],

How can I get get the data of 'value' in 'attributes'? I can get the whole 'attributes' object but can't get to specific values inside, for example

f = open('./metadata/0.json')

xmp = json.load(f)

print (xmp['attributes'])

returns

[{'trait_type': 'Background', 'value': 'Purple'}, {'trait_type': 'Base', 'value': 'RedGuy'}, {'trait_type': 'Body', 'value': 'Formal'}, {'trait_type': 'Hand', 'value': 'FlamingSword'}, {'trait_type': 'Head', 'value': 'RedHead'}, {'trait_type': 'Pet', 'value': 'None'}]

but I only need the value portion. I can run another method to search through it to get what I want but I imagine there is a much easier way.

CodePudding user response:

To get all the values, you need to iterate on 'attributes' and take each 'value' value

xmp = {
    "edition": 979,
    "attributes": [
        {"trait_type": "Background","value": "Gray"},
        {"trait_type": "Base","value": "Guy"},
        {"trait_type": "Body","value": "FormalBlack"},
        {"trait_type": "Hand","value": "None"},
        {"trait_type": "Head","value": "Astronaut"},
        {"trait_type": "Pet","value": "OrangeCat"}
    ],
    "properties": {
      "files": [
        {"uri": "979.png","type": "image/png"}
      ]
    }
}


values = [item['value'] for item in xmp['attributes']]
# ['Gray', 'Guy', 'FormalBlack', ... ]

CodePudding user response:

Just apply a simple filter to the list you already managed to extract:

values = [x['value'] for x in xmp['attributes']]  # if you only want the values
dicts = [{'value': x['value']} for x in xmp['attributes']}  # if you need dicts

CodePudding user response:

Lets say your json variable name is 'data'

You can reach with 2 way.

first one with for loop

for items in data["attributes"]:
print(data['value'])

second one with direct access

print(test['attributes'][0]['value'])

with direct access.

Thanks

  • Related