I have a list of strings like the following
string_list = ['''{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}''', '''{'no" : 1, "name": "John Denver", "address": "454, BohrSt, SA, 64584"}''']
I am trying to convert each string in the list into a dictionary and append it to a dictionary.
import json
newdict = {}
for string in string_list:
new = json.loads(string)
newdict.update(new)
but it is producing an error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
But if I do,
new = json.loads(string_list[1])
It works. And gives the type of new
as <class 'dict'>
. How can I solve this?
I think this one maybe you need
json.loads
to convert the element of string_list
to dictdict comprehension
import json
string_list = ['{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}', '{"no" : 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"}']
print({idx:json.loads(data) for idx,data in enumerate(string_list)})
{
0: {"no": 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"},
1: {"no": 1, "name": "John Doe", "address": "123, Einstein St, SA, 28372"},
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.