12

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)
>>>
2
  • 1
    open the file, read it in as a string, perform json.loads() on that string? As per the answers and some reading into the documentation, json.load() will allow for a file-like object and appears to be a better solution Commented Jul 9, 2020 at 15:44
  • here is a similar question : stackoverflow.com/questions/20199126/reading-json-from-a-file Commented Jul 9, 2020 at 15:45

3 Answers 3

35

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)
Sign up to request clarification or add additional context in comments.

Comments

4

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)

Comments

-9

Try pandas

import pandas as pd
patients_df = pd.read_json('E:/datasets/patients.json')
patients_df.head()

1 Comment

No need to import a library for a simple bug fix.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.