Python Object and JSON String
A Python object is a collection of data in the form of lists, dictionaries, etc. that is stored in memory. A JSON string, on the other hand, is a serialized representation of a JSON object. It is a string of characters that represents the data in the JSON object, but it is not stored in memory as an actual object.
Here is an example of how to use the read()
function to read the contents of students.json
:
with open('students.json', 'r') as file:
json_string = file.read()
print(json_string)
This will output the following:
[{"name": "Alice", "age": 26, "major": "Computer Science"}, {"name": "Bob", "age": 27, "major": "Economics"}, {"name": "Charlie", "age": 25, "major": "Physics"}]
When you try to get the first element of the json_string
, you will get the first character of the string:
print(json_string[0])
[
This is because json_string
is a string, not a list (Python Object). To convert it to a list, we can use the json.loads()
function:
import json
## Convert the JSON string to a Python object
python_object = json.loads(json_string)
print(python_object)
The output is similar to the above, with the difference between single and double quotes.
[{'name': 'Alice', 'age': 26, 'major': 'Computer Science'}, {'name': 'Bob', 'age': 27, 'major': 'Economics'}, {'name': 'Charlie', 'age': 25, 'major': 'Physics'}]
Now we can access the first element of the list:
print(python_object[0])
{ "name": "Alice", "age": 26, "major": "Computer Science" }
Beginners often get Python Object and JSON String confused, so pay special attention.