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))
Related
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']
I'm trying to interpret data from the Twitch API with Python. This is my code:
from twitch.api import v3
import json
streams = v3.streams.all(limit=1)
list = json.loads(streams)
print(list)
Then, when running, I get:
TypeError, "the JSON object must be str, not 'dict'"
Any ideas? Also, is this a method in which I would actually want to use data from an API?
Per the documentation json.loads() will parse a string into a json hierarchy (which is often a dict). Therefore, if you don't pass a string to it, it will fail.
json.loads(s, encoding=None, cls=None, object_hook=None,
parse_float=None, parse_int=None, parse_constant=None,
object_pairs_hook=None, **kw) Deserialize s (a str instance containing
a JSON document) to a Python object using this conversion table.
The other arguments have the same meaning as in load(), except
encoding which is ignored and deprecated.
If the data being deserialized is not a valid JSON document, a
JSONDecodeError will be raised.
From the Twitch API we see that the object being returned by all() is a V3Query. Looking at the source and documentation for that, we see it is meant to return a list. Thus, you should treat that as a list rather than a string that needs to be decoded.
Specifically, the V3Query is a subclass of ApiQuery, in turn a subclass of JsonQuery. That class explicitly runs the query and passes a function over the results, get_json. That source explicitly calls json.loads()... so you don't need to! Remember: never be afraid to dig through the source.
after streams = v3.streams.all(limit=1)
try using
streams = json.dumps(streams)
As the streams should be a JSON string and be in the form:
'{"key":value}'
instead of just dict form:
{"key":value}
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": {
...
},
...
}
Am trying to extract command line arguments passed in python
cmdargs = str(sys.argv)
print cmdargs
it prints
['E:/omation.py', '{"command":"sel_media","value":"5X7_phot
o_paper.png"},{"command":"tray","value":"4X6_photo_paper.png"}']
from this how can i extract command and values .
i dont knoe how to loop this array and get the commnd and value values.plese help
Note: i also want to discard the first value 'E:/omation.py'
You can use Python utils to parse json strings:
import json
examples = json.loads('['+cmdargs[1]+']')
The first import loads json utilities for python. Then, you can parse a json string into a Python dictionary by using json.loads. In the example, I have parsed one of your json strings into a python dictionary. Remember to add '[' and ']' to convert your string to a valid json array. Then, you can get a command and a value like :
print(examples[0]['command'])
print(examples[0]['value' ])
The example you give shows two json objects in the second element of the list cmdargs. Probably the easiest way to capture that case would be to enclose that second argument in square braces, which would make it legal JSON, then loop through the resulting list:
import json
a = json.loads('['+cmdargs[1]+']')
for p in a:
print "command is ", p['command']
print "value is ", p['value']
This is specific to the example you showed, you may need to make it more robust for your purposes.
Your input is not valid JSON. You must find a way to pass the arguments as separate, valid JSON objects. Then you can do this:
# j.py
import json
import sys
print(sys.argv)
for arg in sys.argv[1:]:
j = json.loads(arg)
print(j.get("command"))
print(j.get("value"))
Usage could be:
$ python3 j.py '{"command":"sel_media","value":"5X7_photo_paper.png"}' '{"command":"tray","value":"4X6_photo_paper.png"}'
['j.py', '{"command":"sel_media","value":"5X7_photo_paper.png"}', '{"command":"tray","value":"4X6_photo_paper.png"}']
sel_media
5X7_photo_paper.png
tray
4X6_photo_paper.png
I have an output :
result = {
"sip_domains":{
"prefix":[{"name":""}],
"domain":[{"name":"k200.com"},{"name":"Zinga.com"},{"name":"rambo.com"}]
},
"sip_security":{"level":2},
"sip_trusted_hosts":{"host":[]},
"sip_proxy_mode":{"handle_requests":1}
}
from this i just wanted the output to print to my screen :
domain : k200.com
domain : Zinga.com
domain : rambo.com
how can i get this output using regular expression
Help needed urgently
If it's the text you need to parse then Use JSON module to parse the JSON payload:
http://docs.python.org/library/json.html?highlight=json#json
Regular expression are not needed with good programming language like Python.
Otherwise if it's Python dictionary then use Python dictionary [] style item access to read data from the dictionary.
If you are getting this data as a string from somewhere you must convert it to a python dictionary object to access it. You should not have to use any regular expressions to get this output.
import json
# get the json str somehow
json_dict = json.loads(json_str)
for domain_dict in json_dict['sip_domains']['domain']:
print 'domain : %s' % (domain_dict['name'])