How to access json in python - python

I am trying to access json object in python and I am running through different errors
this is the data
value = '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'
I will like to get
"05-16-13","counter":3
"05-18-13","counter":1
I did
for info in value:
print info['counter']
I keep getting a type error, any help?
TypeError: string indices must be integers, not str

Use json.loads to convert it into a Python dictionary:
import json
value = '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'
d = json.loads(value)
for key, info in d.items():
print info['counter']
The error you were getting before was because string objects should be indexed by integers.
Let's take a completely different string and see why:
'abcd'[0] # 'a'
'abcd'['xyx'] # What does this even mean? TypeError!
'{"0":{"created":"05-16-13","counter":3}"}'['couter'] # TypeError for the same reasons.

There is a json library that you can import and use in Python. You can see docs for Python 3 here and Docs for Python 2 here.
import json
value = '{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}'
value = json.loads(value)
print(value[0])

Because value is a string. You should parse the json in it to access to its elements:
import json
value = json.loads('{"0":{"created":"05-16-13","counter":3},"1":{"created":"05-17-13","counter":1},"2":{"created":"05-18-13","counter":1}}')
for info in value.items():
print info['counter']

Related

Get value for only one JSON variable

I want to get the value for last with Python, using requests and json. I have this:
import requests
import json
res = requests.get('https://www.bitstamp.net/api/v2/ticker/btcusd/')
print res.json['last']
But it showed me this:
TypeError: 'instancemethod' object has no attribute '__getitem__'
It's working to get all JSON code with res.json() but I want only the value from 'last'.
res.json() will parse the responses json object, which you need to do, to access any value of it. So to access the value last, you need to do: res.json()['last']

ValueError: malformed string

I am working with an API which returns the following unicode as response:
dd = u"""{"meta":{"request":{"granularity":"Weekly","main_domain_only":false,
"domain":"borivali.me",
"country":"world"},"status":"Success",
"last_updated":"2016-05-09"},"bounce_rate":[{"date":"2016-04-12","bounce_rate":0.5},
{"date":"2016-04-19","bounce_rate":0.13355382826388454},
{"date":"2016-04-26","bounce_rate":0.0},
{"date":"2016-05-03","bounce_rate":0.23602940883106352}]}"""
I'm trying to parse this information in the following way:
ddd = ast.literal_eval(dd)
print ddd
However, I get the following error:
ValueError: malformed string
What seems to be wrong with my code?
PS: dd stores a unicode string and not a dictionary.
Assuming following definition is correct:
s = u"""{"meta":{"request":{"granularity":"Weekly","main_domain_only":false,
"domain":"borivali.me",
"country":"world"},"status":"Success",
"last_updated":"2016-05-09"},"bounce_rate":[{"date":"2016-04-12","bounce_rate":0.5},
{"date":"2016-04-19","bounce_rate":0.13355382826388454},
{"date":"2016-04-26","bounce_rate":0.0},
{"date":"2016-05-03","bounce_rate":0.23602940883106352}]}"""
Given that declaration, s is JSON document and may be parsed to Python objects with json library.
import json
p = json.loads(s)
ast module is used to deserialise repr of Python objects, and repr does not equal JSON serialization in general case. Following relations holds (at least for simple Python types, well defined in JSON standard - lists, dicts and strings).
d == ast.literal_eval(repr(d))
d == json.loads(json.dumps(d))

TypeError: list indices must be integers or slices, not str while parsing JSON

I am trying to print out at least one key value from the returned Json, as following this basic tutorial
response=None
booking_source = 'sourceBusinessName'
api_request ='http://api.com'
r = requests.get(api_request)
while response is None:
response = r.content.decode('utf-8')
data = json.loads(response)
print (data[booking_source])
return HttpResponse(data[booking_source])
But it returns TypeError: list indices must be integers or slices, not str
probably because I am giving an string instead of an integer to data when printing, but then what I am doing wrong here ?
With requests you can skip the decoding of the response and parsing it as JSON by using the response's json method:
r = requests.get(api_request)
data = r.json()
print data # so you can see what you're dealing with
At this point I suggest dumping out the value of data so that you can see the structure of the JSON data. Probably it is a JSON array (converted to a Python list) and you simply need to take the first element of that array before accessing the dictionary, but it's difficult to tell without seeing the actual data. You might like to add a sample of the data to your question.
Your JSON is an array at the top level, but you're trying to address it as if it were:
{
"sourceBusinessName": {
...
},
...
}

Printing output from json

I am still new to python, and brand new to json. I am trying to go through output that is in json. I am not yet sure which fields will need to be printed out, but I do know that two of them will be needed.
How could I change:
import json
from pprint import pprint
with open('out.json') as data_file:
data = json.load(data_file)
pprint(data)
to print out say, field one, and field two?
I figure if I can print field one, and two, I can play around with it until I find the right fields. I imagine this is a derp level question, but being able to print specific fields is what I need to be able to do.
json.load is returning python obj (https://docs.python.org/3/library/json.html#json.load) so depending on content of 'out.json' it can be either dict, list or few other types.
In case of dictionary you can go with data['key'] or if it's list go with data[index] - where index is 1,2,...
For looping use for ie for list:
for elem in data:
print(elem)
of for dictionary:
for key, value in data.items():
print(key, value)
You could have find it easily in python's json documentation.
Here data is a dict type object. You can get any value by using the corresponding key like this:
print data['field']
But it will throw a KeyError if the field key is not present in the dict. For avoiding this issue you can use the get() method.
print data.get('field')
This will return None in case of missing key.

Pass a variable to extract from JSON String in Python?

I have below JSON String. Now I want to extract each individual field from that JSON string.
So I decided to create a method parse_json which will accept a variable that I want to extract from the JSON String.
Below is my python script -
#!/usr/bin/python
import json
jsonData = '{"pp": [0,3,5,7,9], "sp": [1,2,4,6,8]}'
def parse_json(data):
jj = json.loads(jsonData)
return jj['+data+']
print parse_json('pp')
Now whenever I an passing pp to parse_json method to extract its value from the JSON String, I always get the error as -
return jj['+data+']
KeyError: '+data+'
Any idea how to fix this issue? As I need to pass the variable which I am supposed to extract from the JSON String?
You probably just want this:
return jj[data]
Your code is trying to look up a key named literally '+data+', when instead what you want to do is look up the key with a name of the function's parameter.
Just use data parameter itself.
Replace following line:
return jj['+data+'] # lookup with `+data+`, not `pp`
with:
return jj[data]

Categories

Resources