I am asked to generate and also later read back a json object which looks like:
{"name":"somename",
[{"id":123,"key1":"anydata"},
{"id":345,"key1":"x","key3":"yz"}]}
Normally, I would use a python dict and convert it to/from json. Here however is the problem, that both, list and sub-dict are anonymous.
I think it is not possible to make a dict like this, is it?
This is not a valid json object but you can just add a key for the list part. Like:
{"name":"somename","value" : [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]}
Now this is a valid json string.
>>> a = ast.literal_eval('{"name":"somename","value" : [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]}')
>>> print(a['name'])
>>> 'somename'
>>> print(a['value'][0]['id'])
>>> 123
For a variable list its is as simple as:
anon_list = [{"id":123,"key1":"anydata"},{"id":345,"key1":"x","key3":"yz"}]
a = {"name":"somename","value" : anon_list}
>>> print(a['name'])
>>> 'somename'
>>> print(a['value'][0]['id'])
>>> 123
Related
I'm having trouble converting the below JSON string to type dict. json.loads throws an error because of the two sets of squiggles: {}, {}
test = '{"124074": "0.0944", "124111": "0.0809", "124194": "0.0788"}, {"128213": "0.39", "129043": "0.458", "129054": "0.378"}'
Any thoughts on how I fix this? I need to be able to convert to dict so I can iterate through the keys. Should the JSON string be represented in a different way?
Based on the comment from #rv.kvetch, one can get the following result
>>> test = '{"124074": "0.0944", "124111": "0.0809", "124194": "0.0788"}, {"128213": "0.39", "129043": "0.458", "129054": "0.378"}'
>>> dicts = json.loads(f'[{test}]')
>>> dicts
[{'124074': '0.0944', '124111': '0.0809', '124194': '0.0788'}, {'128213': '0.39', '129043': '0.458', '129054': '0.378'}]
>>> dicts[0]
{'124074': '0.0944', '124111': '0.0809', '124194': '0.0788'}
>>> type(dicts[0])
<class 'dict'>
essentially a list of dicts is created instead of a single dict.
I need to convert a string of list to List in Python. I have seen many of the similar questions but none of them works in this case.
I am passing some values through PostMan.
The key passing as a form data
Key = controls
value = [CR1,CR2]
I am fetching the data like this
c_list = self._kwargs['data'].get('controls', [])
print(c-list)
print(type(c-list))
I am getting the following o/p
[CC-2,CC-3]
<class 'str'>
But I need to get it as a list so I have tried the following method
import ast
c_list = self._kwargs['data'].get('controls', [])
res = ast.literal_eval(c_list)
But I am getting the following Error
malformed node or string: <_ast.Name object at 0x7f82966942b0>
You could simply do the following: strip the brackets and split on the commas
>>> s = "[CC-2,CC-3]"
>>> s.strip('[]').split(',')
['CC-2', 'CC-3']
Is there a simple way to create a dictionary from a list of formatted tuples. e.g. if I do something like:
d={"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
This creates a dictionary called d. However, if I want to create a dictionary from a string which contains the same string, I can't do that
res=<some command that returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}>
print res
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
d=dict(res)
This throws an error that says:
ValueError: dictionary update sequence element #0 has length 1; 2 is required
I strongly strongly suspect that you have json on your hands.
import json
d = json.loads('{"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}')
would give you what you want.
Use dict(zip(tuples))
>>> u = ("foo", "bar")
>>> v = ("blah", "zoop")
>>> d = dict(zip(u, v))
>>> d
{'foo': 'blah', 'bar': 'zoop'}
Note, if you have an odd number of tuples this will not work.
Based on what you gave is, res is
# returns {"responseStatus":"SUCCESS","sessionId":"01234","userId":2000004904}
So the plan is to grab the string starting at the curly brace to the end and use json to decode it:
import json
# Discard the text before the curly brace
res = res[res.index('{'):]
# Turn that text into a dictionary
d = json.loads(res)
All you need to do in your particular case is
d = eval(res)
And please keep security in mind when using eval, especially if you're mixing it with ajax/json.
UPDATE
Since others pointed out you might be getting this data over the web and it isn't just a "how to make this work" question, use this:
import json
json.loads(res)
I am trying to convert a string to a dictionary with dict function, like this
import json
p = "{'id':'12589456'}"
d = dict(p)
print d['id']
But I get the following error
ValueError: dictionary update sequence element #0 has length 1; 2 is required
Why does it fail? How can I fix this?
What you have is a string, but dict function can only iterate over tuples (key-value pairs) to construct a dictionary. See the examples given in the dict's documentation.
In this particular case, you can use ast.literal_eval to convert the string to the corresponding dict object, like this
>>> p = "{'id':'12589456'}"
>>> from ast import literal_eval
>>> d = literal_eval(p)
>>> d['id']
'12589456'
Since p is a string containing JSON (ish), you have to load it first to get back a Python dictionary. Then you can access items within it:
p = '{"id":"12589456"}'
d = json.loads(p)
print d["id"]
However, note that the value in p is not actually JSON; JSON demands (and the Python json module enforces) that strings are quoted with double-quotes, not single quotes. I've updated it in my example here, but depending on where you got your example from, you might have more to do.
i have a string
'''
{"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":164
23386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66
64a1679bbeed4282154b35"}
'''
how to get the value .
thanks
>>> import json
>>> s=''' {"session_key":"3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986","uid":16423386,"expires":12673200,"secret":"sm7WM_rRtjzXeOT_jDoQ__","sig":"6a6aeb66 64a1679bbeed4282154b35"} '''
>>> d=json.loads(s)
>>> d['session_key']
u'3.KbRiifBOxY_0ouPag6__.3600.1267063200-16423986'
>>> d['uid']
16423386
>>> d['expires']
12673200
>>> d['secret']
u'sm7WM_rRtjzXeOT_jDoQ__'
>>> d['sig']
u'6a6aeb66 64a1679bbeed4282154b35'
>>>
The string appears to be JSON.
import json
obj= json.loads( aString )
obj['session_key']
Or it could be a Python dict. Try
obj= eval(myString)
obj['session_key']
For a simple-to-code method, I suggest using ast.parse() or eval() to create a dictionary from your string, and then accessing the fields as usual. The difference between the two functions above is that ast.parse can only evaluate base types, and is therefore more secure if someone can give you a string that could contain "bad" code.