import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
print(data['fruits'])
# the print displays:
# ['apple', 'banana', 'orange']
You had everything you needed. data will be a dict, and data['fruits'] will be a list
Tested on Ideone.
import json
array = '{"fruits": ["apple", "banana", "orange"]}'
data = json.loads(array)
fruits_list = data['fruits']
print fruits_list
Your JSON data is a list of dictionaries, so after json.loads(s) you will have jdata as a list, not a dictionary.
Try something like the following:
import json
s = '[{"i":"imap.gmail.com","p":"someP@ss"},{"i":"imap.aol.com","p":"anoterPass"}]'
jdata = json.loads(s)
for d in jdata:
for key, value in d.iteritems():
print key, value
json.loads(s) will return you list. To iterate over it you don't need iteritems.
>>> jdata = json.loads(s)
>>> for doc in jdata:
... for key, value in doc.iteritems():
... print key, value
decode JSON strings into dicts and put them in a list, last, convert the list to JSON
json_list = []
json_list.append(json.loads(JSON_STRING))
json.dumps(json_list)
or more pythonic syntax
output_list = json.dumps([json.loads(JSON_STRING) for JSON_STRING in JSON_STRING_LIST])
Use json.dumps before json.loads to convert your data to dictionary object This also helps prevent valueError: Expecting property name enclosed in double quotes.
Ex:
import json
myJSONStringList = ['{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}',
'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
print([json.loads(json.dumps(i)) for i in myJSONStringList])
Output:
[u'{"user": "testuser", "data": {"version": 1, "timestamp": "2018-04-03T09:23:43.388Z"}, "group": "33"}', u'{"user": "otheruser", "data": {"version": 2, "timestamp": "2018-04-03T09:23:43.360Z", }, "group": "44"}']
Just adding onto alexce's response, you can easily convert the restructured data into JSON:
import json
json.dumps(result)
There are some potential security concerns with top-level arrays. I'm not sure if they're still valid with modern browsers, but you may want to consider wrapping it in an object.
import json
json.dumps({'results': result})
To solve this, you need to split the input list into chunks, by 7 in your case. For this, let's use this approach. Then, use a list comprehension producing a list of dictionaries:
>>> from pprint import pprint
>>> l = [['String 1'],['String 2'],['String 3'],['String 4'],['String 5'],
... ['String 6'],['String 7'],['String 8'],['String 9'],['String 10'],
... ['String 11']]
>>> def chunks(l, n):
... """Yield successive n-sized chunks from l."""
... for i in range(0, len(l), n):
... yield l[i:i+n]
...
>>>
>>> result = [{"title%d" % (i+1): chunk[i][0] for i in range(len(chunk))}
for chunk in chunks(l, 7)]
>>> pprint(result)
[{'title1': 'String 1',
'title2': 'String 2',
'title3': 'String 3',
'title4': 'String 4',
'title5': 'String 5',
'title6': 'String 6',
'title7': 'String 7'},
{'title1': 'String 8',
'title2': 'String 9',
'title3': 'String 10',
'title4': 'String 11'}]
I'm assuming, you have double-encoded json. Just call another json.loads() on values of second dictionaries:
import json
json_text = r'''{
"1": {
"Data (L)": "[ { \"S\" : \"168\" }]"
},
"2": {
"Data (L)": "[ { \"S\" : \"169\" }]"
}
}'''
data = json.loads(json_text)
for k, v in data.items():
for kk, vv in v.items():
vv = json.loads(vv)
print(type(vv))
print(vv)
Prints:
<class 'list'>
[{'S': '168'}]
<class 'list'>
[{'S': '169'}]
It is not a recommend method!
It is not secure to use eval() function this way. See Eval really is dangerous. (Thanks to @KarlKnechtel
for the comment!)
Instead ast.literal_eval() can be used. See Using python's eval() vs. ast.literal_eval()?. (Thanks to @Sushanth for the comment!)
Initial answer below
You can use the built-in eval() function like the following:
s = "[ { \"S\" : \"168\" }]"
t = eval(s)
print(t)
print(type(t))
print(t[0])
print(type(t[0]))
which prints
[{'S': '168'}]
<class 'list'>
{'S': '168'}
<class 'dict'>
This should do the job:
result = None
with open("filename", 'r') as fh:
result = [json.loads(line) for line in fh]
Or you can use map instead of list comprehensions as @JeffS said
result = None
with open("filename", 'r') as fh:
result = map(json.loads, fh)
Use the json module for loading JSON. (Pre-2.6 use the third party simplejson module, which has the same exact API.)
>>> import json
>>> f = open(‘json.file’,'r’)
>>> d = json.loads(f.read())
>>> print d
or use the old hack using the similarity between json and python dict syntax, but only use this hack if you are sure that json file does not contain json comment ..
f = open('json.file','r')
d = eval(f.read())