hi I want to read a JSON file in python and any kind of syntax that i use i receive an error and i don't know what to do the code :
import urllib
import pprint
import json
import re
import requests
import pprint
with open('synsets.json' , encoding = 'utf-8') as json_data:
d = json.loads(json_data.read())
json_data.close()
pprint(d)
the error :
Traceback (most recent call last):
File "D:\markaz\wikiomega\code1.py", line 13, in <module>
d = json.loads(json_data.read())
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\lib\json\__init__.py", line 319, in loads
return _default_decoder.decode(s)
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\BehnaM1\AppData\Local\Programs\Python\Python35-32\lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[Finished in 0.7s with exit code 1]
Related
I want to read a JSON file with Python :
Here is part of my JSON file :
{ "Jointure":[ { "IDJointure":1, "societe":"S.R.T.K", "date":"2019/01/01", "heure":"05:47:00"}, { "IDJointure":2, "societe":"S.R.T.K", "date":"2019/01/01", "heure":"05:50:00"}]}
This is the code :
import json
data = json.loads('Data2019.json')
for i in data['Jointure']:
print(i)
But, here is the error that was displayed
Traceback (most recent call last):
File "C:\Users\HP\Desktop\readJSON.py", line 4, in <module>
data = json.loads('Data2019.json')
File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\json\__init__.py", line 357, in loads
return _default_decoder.decode(s)
File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\HP\AppData\Local\Programs\Python\Python38\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
>>>
json.loads() expects the json data to already be a string -- so it's trying to interpret the filename Data2019.json as actual json data.
Open the file, and then pass the file object to json.load():
with open('Data2019.json') as fp:
data = json.load(fp)
don't read the file directly. Open the file it's only the contents of the file that works with the json module. Try this:
import json
with open('path_to_file/person.json') as f:
data = json.load(f)
Try pandas
import pandas as pd
patients_df = pd.read_json('E:/datasets/patients.json')
patients_df.head()
[{"answerInfo":{"extraData":{"am_answer_type":"NN"}},"content":"MP3:not support.","messageId":"c4d6a2f4649d483a811fcce4b26ae9a1"}]
How to extract "MP3: not support" from this String using regular expression or python code?
But an error was generated per the suggestion:
Traceback (most recent call last):
File "/Users/congminmin/PycharmProjects/Misc/csv/csvLoader.py", line 16, in <module>
print(question+ " " + json.loads(answer)[0]['content'])
File "/Users/congminmin/anaconda3/lib/python3.6/json/__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "/Users/congminmin/anaconda3/lib/python3.6/json/decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/Users/congminmin/anaconda3/lib/python3.6/json/decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
Python 3.6.5 (default, Jun 17 2018, 12:13:06)
>>> text = '[{"answerInfo":{"extraData":{"am_answer_type":"NN"}},"content":"MP3:not support.","messageId":"c4d6a2f4649d483a811fcce4b26ae9a1"}]'
>>> import json
>>> json.loads(text)[0]['content']
'MP3:not support.'
I would suggest to use json instead of regex based on your sample.
Check it running here
import json
json_data = '[{"answerInfo":{"extraData":{"am_answer_type":"NN"}},"content":"MP3:not support.","messageId":"c4d6a2f4649d483a811fcce4b26ae9a1"}]'
python_obj = json.loads(json_data)
print(python_obj[0]["content"])
I am uploading a file to a REST API with a Python 3 script via the windows command line. The filename is an argument passed in to the script. Everything works fine unless there is a space in the path name. i.e. c:\temp\myFolder\1.jpg works, but c:\temp\my Folder\1.jpg throws an error:
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
The code up until the error is as follows:
def upload_photo(filename):
f = open(filename, "rb")
data = f.read()
data_md5 = hashlib.md5(data).hexdigest()
f.close()
r = requests.put('https://upload.mysite.com/{}'.format(filename), data=data)
response = json.loads(r.text)
I'm not sure how to fix it. Thanks for the help.
--Edit--
Full traceback
c:\>python test.py "c:/temp/my folder/1.jpg"
Traceback (most recent call last):
File "test.py", line 144, in <module>
print(test(sys.argv[1]))
File "test.py", line 132, in upload_photo
response = json.loads(r.text)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\__init__.py", line 348, in loads
return _default_decoder.decode(s)
File "C:\Users\Default\AppData\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 337, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\Users\Default\Default\Local\Programs\Python\Python37-32\lib\json\decoder.py", line 355, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
You need to encode the link properly; escaping the invalid character(s). You can do that with urllib.
>>> import urllib
>>> filename = urllib.parse.quote('c:\temp\my Folder\1.jpg')
>>> 'https://upload.mysite.com/' + filename
'https://upload.mysite.com/c%3A%09emp%5Cmy%20Folder%01.jpg'
I'm a newbie into Python and i'm trying to open a json file that looks like this:
{
"empty_char":"",
"empty_number": ,
"char":"i'm a char",
"number":0
}
Let's say that this is the test.json file:
When trying to open it in python I'm using:
import json
with open('test.json') as f:
data = json.load(f)
and it raises the following error:
Traceback (most recent call last):
File "<input>", line 2, in <module>
File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 299, in load
parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)
File "C:\ProgramData\Anaconda3\Lib\json\__init__.py", line 354, in loads
return _default_decoder.decode(s)
File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 339, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "C:\ProgramData\Anaconda3\Lib\json\decoder.py", line 357, in raw_decode
raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 3 column 19 (char 39)
It gives an error because of "empty_number": ,
How can I deal with this error if I can't modify my .json file?
You can use the more flexible yaml to read in values not provided as None.
import yaml
from io import StringIO
mystr = StringIO("""{
"empty_char":"",
"empty_number": ,
"char":"i'm a char",
"number":0
}""")
# replace mystr with open('test.json', 'r')
with mystr as stream:
res = yaml.load(stream)
print(res, type(res))
{'empty_char': '', 'empty_number': None, 'char': "i'm a char", 'number': 0}
<class 'dict'>
Note io.StringIO lets us read from a string as if it were a file.
After executing the following code:
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
json.loads(a)
I get:
Traceback (most recent call last):
File "", line 1, in
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/init.py", line 338, in loads
return _default_decoder.decode(s)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 365, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/json/decoder.py", line 381, in raw_decode
obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)
So how can I convert 'a' to dict.
Please note that the string is already in 'a' and I cannot add 'r' in front of it. Ideally, the string should have been {"excludeTypes":"*.exe;~\\\\$*.*"}
Also, the following code doesn't work:
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
b = repr(a)
json.loads(b)
import ast
d = ast.literal_eval(a)
By escaping Escape Character "\":
import json
a = '{"excludeTypes":"*.exe;~\\$*.*"}'
a = a.replace("\\","\\\\")
json.loads(a)