Reputation: 372
I am trying to convert a JSON file into python dict. but I failed.
Here is my JSON file:
me.json
:
{
"title": "this is title",
"Description": " Fendi is an Italian luxury labelarin. ",
"url": "https:/~"
}
{
"title": " - Furrocious Elegant Style",
"Description": " the Italian luxare vast. ",
"url": "https://www.s"
}
{
"title": "Rome, Fountains and Fendi Sunglasses",
"Description": " Fendi started off as a store. ",
"url": "https://www.~"
}
{
"title": "Tipsnglasses",
"Description": "Whether irregular orn season.",
"url": "https://www.sooic"
}
and this is my python code:
import json
with open('me.json', 'r') as obj:
a = obj.read()
for i in a:
medict = dict(i)
I don't know why it is not working, what is wrong with it.
Can anyone help me in this case?
Upvotes: 0
Views: 77
Reputation: 123541
You could use the re
module to find JSON objects in the input file (which isn't strictly in JSON format) as it is shown in your question (i.e. no need to modify it):
import ast
import json
from pprint import pprint
import re
with open('me.json', 'r') as obj:
data = obj.read()
matches = re.findall(r'({.+?})', data, re.DOTALL)
result = [json.loads(m) for m in matches]
pprint(result)
Output:
[{'Description': ' Fendi is an Italian luxury labelarin. ',
'title': 'this is title',
'url': 'https:/~'},
{'Description': ' the Italian luxare vast. ',
'title': ' - Furrocious Elegant Style',
'url': 'https://www.s'},
{'Description': ' Fendi started off as a store. ',
'title': 'Rome, Fountains and Fendi Sunglasses',
'url': 'https://www.~'},
{'Description': 'Whether irregular orn season.',
'title': 'Tipsnglasses',
'url': 'https://www.sooic'}]
Upvotes: 0
Reputation: 1779
Please use json.loads
.
But, You have to change the data in file as json format first. Please use the following data.
I added [
, ]
and ,
.
[{
"title": "this is title",
"Description": " Fendi is an Italian luxury labelarin. ",
"url": "https:/~"
}
,
{
"title": " - Furrocious Elegant Style",
"Description": " the Italian luxare vast. ",
"url": "https://www.s"
}
,
{
"title": "Rome, Fountains and Fendi Sunglasses",
"Description": " Fendi started off as a store. ",
"url": "https://www.~"
}
,
{
"title": "Tipsnglasses",
"Description": "Whether irregular orn season.",
"url": "https://www.sooic"
}]
And, Refer the following code:
import json
with open('me.json', 'r') as obj:
a = obj.read()
medict = json.loads(a)
print (medict)
The result is :
[{'title': 'this is title', 'Description': ' Fendi is an Italian luxury labelarin. ', 'url': 'https:/~'}, {'title': ' - Furrocious Elegant Style', 'Description': ' the Italian luxare vast. ', 'url': 'https://www.s'}, {'title': 'Rome, Fountains and Fendi Sunglasses', 'Description': ' Fendi started off as a store. ', 'url': 'https://www.~'}, {'title': 'Tipsnglasses', 'Description': 'Whether irregular orn season.', 'url': 'https://www.sooic'}]
Upvotes: 1