Trying to Open a Jason file but keep getting error

Question:
I am trying to open a json file but I keep getting an error. Does anybody know what is the problem with my code?
Repl link:
https://replit.com/@jonathanessombe/learn-1#main.py

# JSON = Javascript Object Notation

import json

with open('Student.py', 'r') as f:
  data = json.load(f)

print(data)


json_string =''' 
  {
      "students": [
        {
            "id":1,
            "name":"Jason",
            "age": 21,
            "full_name":true
        },
        {
            "id":2,
            "name":"Joe",
            "age": 33,
            "full_name": false
        }
      ] 
  }
'''

data = json.loads(json_string)
data['test'] = True

new_json = json.dumps(data, indent=4, sort_keys=True)
print(new_json)

#File code
{
  "students": [
    {
        "id": 1,
        "name": "Jason",
        "age": 21,
        "full_name": true
    },
    {
        "id": 2,
        "name": 'Joe',
        "age": 33,
        "full_name": false
    }
  ]
}
  

You are trying to load a file named student.py using json.load(f) , but it seems like you want to load the JSON data from the provided JSON string instead of a file. If you intend to load the data from the string, you should use json.loads(json_string) instead of reading from a file.

Fixed code:

import json

json_string = '''{
    "students": [
        {
            "id": 1,
            "name": "Jason",
            "age": 21,
            "full_name": true
        },
        {
            "id": 2,
            "name": "Joe",
            "age": 33,
            "full_name": false
        }
    ]
}'''

data = json.loads(json_string)

for student in data["students"]:
    student["full_name"] = True if student["full_name"] else False

data["test"] = True

new_json = json.dumps(data, indent=4, sort_keys=True)
print(new_json)

The issue is you have single quotes (') around Joe, rather than double quotes ("), which would denote a string.

4 Likes

we can’t use strings with single quotes in a json file?

Yeah that surprised me too when I realised that, it seems JSON is stricter than JavaScript and only allows double quotes.