简体   繁体   中英

How to access element in json using python?

I need help on how do I use python to access element from JSON structure.

Assuming I have a JSON like this

{
'result':
  [
    {
     'aa':1, 
     'bb':2
    },
    {
     'cc':3, 
     'dd':4
    }
  ]
 }

In python, how exactly to get the data for aa or dd ? I tried with

str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}
str1new = str1['result']['aa]

but it gives me error

list indices must be integers, not str

How do I solve this? Is there any other method using python to get the data from JSON? Thank you for the help. I really appreciated it.

Try this and for the next ones use indexes like 1 or 2 if you have more, or you can loop if you have multiple indexes within the json .

str1new = str1['result'][0]['aa']

In python if you write:

str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}

it's dictionary and not json.

if your input is having json string you need to use

import json

json_str = """{
"result":
  [
    {
     "aa":1, 
     "bb":2
    },
    {
     "cc":3, 
     "dd":4
    }
  ]
 }"""
str1 = json.loads(json_str)

then you can use similar to python dictionary.

as answered by others you can then use

aa = str1['result'][0]['aa']

try

str1new = str1['result'][0]['aa]

As str1['result'] is a list, that's why you're getting list indices must be integers, not str error.

aa = str1['result'][0]['aa']
dd = str1['result'][1]['dd']

result is a list, so you need to reference a valid index before accessing aa :

str1 = {'result':[{'aa':1, 'bb':2},{'cc':3, 'dd':4}]}
str1new = str1['result'][0]['aa']

In Python, unless you're using a package (then specify it), "JSON" structure are actually dicts.

{
'result':
  [
    {
     'aa':1, 
     'bb':2
    },
    {
     'cc':3, 
     'dd':4
    }
  ]
 }

Here, your dict has only one key: result . Its values are contained in a list. This list is a list of dicts. So use cascade index access to get your aa value:

str1['result'][0]['aa']

For Python3, using the Json library you can easily parse Json.

# import statement
import json

# using example sting from above
jsonString = '{ "result" : [{ "aa": 1,"bb": 2 }, { "cc": 3, "dd": 4 }]}'

# parse json string
parsedJsonObject = json.loads(jsonString)

# access a specific property in the json object 
resultObject = parsedJsonObject['result']

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