Ling
Ling

Reputation: 911

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.

Upvotes: 3

Views: 23837

Answers (7)

benhorgen
benhorgen

Reputation: 1975

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']

Upvotes: 0

Rahul
Rahul

Reputation: 11560

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']

Upvotes: 2

Exprator
Exprator

Reputation: 27533

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']

Upvotes: 6

Thomas Dussaut
Thomas Dussaut

Reputation: 746

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']

Upvotes: 1

K. Kirsz
K. Kirsz

Reputation: 1420

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']

Upvotes: 1

pramod
pramod

Reputation: 1493

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']

Upvotes: 1

Arpit Solanki
Arpit Solanki

Reputation: 9931

try

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

Upvotes: 1

Related Questions