Reputation: 305
I have a list like this:
mylist = ['{"data": {"id": "854652314"', '"value": 854652314', '"name": "854652314"}}', '{"data": {"id": "B2"', '"value": "B2"', '"name": "B2"}}', '{"data": {"id": "457856954"', '"value": 457856954', '"name": "457856954"}}']
I would like to convert strings to dictionary.
I've tried this code:
res = [json.loads(idx.replace("'", '"')) for idx in mylist]
print(res)
But I get an error:
json.decoder.JSONDecodeError: Expecting ',' delimiter: line 1 column 28 (char 27)
May I know how to solve the error?
Upvotes: 0
Views: 66
Reputation: 580
You could convert the list to a string literal, remove all unwanted symbol ('), and convert it back using eval()
mylist = ['{"data": {"id": "854652314"', '"value": 854652314', '"name": "854652314"}}', '{"data": {"id": "B2"', '"value": "B2"', '"name": "B2"}}', '{"data": {"id": "457856954"', '"value": 457856954', '"name": "457856954"}}']
mylist = str(mylist).replace("'", "")
mylist = eval(mylist)
print(mylist)
Output
[{'data': {'id': '854652314', 'value': 854652314, 'name': '854652314'}}, {'data': {'id': 'B2', 'value': 'B2', 'name': 'B2'}}, {'data': {'id': '457856954', 'value': 457856954, 'name': '457856954'}}]
Upvotes: 0
Reputation: 14684
Try this:
jsons = []
current = []
for i, m in enumerate(mylist):
if m.startswith('{"data":') and i > 0:
jsons.append(", ".join(current))
current = [m]
else:
current.append(m)
jsons.append(", ".join(current))
data = [json.loads(j) for j in jsons]
Upvotes: 2
Reputation: 911
Try this approach, I have formatted list..
import json
mylist = ['{"data": {"id": "854652314", "value": "854652314", "name": "854652314"}}', '{"data": {"id": "B2", "value": "B2", "name": "B2"}}', '{"data": {"id": "457856954", "value": "457856954", "name": "457856954"}}']
res = [json.loads(idx) for idx in mylist]
print(res)
Upvotes: -1