Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

Answer from DaoWen on Stack Overflow
Top answer
1 of 6
365

Your JSON is an array with a single object inside, so when you read it in you get a list with a dictionary inside. You can access your dictionary by accessing item 0 in the list, as shown below:

json1_data = json.loads(json1_str)[0]

Now you can access the data stored in datapoints just as you were expecting:

datapoints = json1_data['datapoints']

I have one more question if anyone can bite: I am trying to take the average of the first elements in these datapoints(i.e. datapoints[0][0]). Just to list them, I tried doing datapoints[0:5][0] but all I get is the first datapoint with both elements as opposed to wanting to get the first 5 datapoints containing only the first element. Is there a way to do this?

datapoints[0:5][0] doesn't do what you're expecting. datapoints[0:5] returns a new list slice containing just the first 5 elements, and then adding [0] on the end of it will take just the first element from that resulting list slice. What you need to use to get the result you want is a list comprehension:

[p[0] for p in datapoints[0:5]]

Here's a simple way to calculate the mean:

sum(p[0] for p in datapoints[0:5])/5. # Result is 35.8

If you're willing to install NumPy, then it's even easier:

import numpy
json1_file = open('json1')
json1_str = json1_file.read()
json1_data = json.loads(json1_str)[0]
datapoints = numpy.array(json1_data['datapoints'])
avg = datapoints[0:5,0].mean()
# avg is now 35.8

Using the , operator with the slicing syntax for NumPy's arrays has the behavior you were originally expecting with the list slices.

2 of 6
31

Here is a simple snippet that read's in a json text file from a dictionary. Note that your json file must follow the json standard, so it has to have " double quotes rather then ' single quotes.

Your JSON dump.txt File:

{"test":"1", "test2":123}

Python Script:

import json
with open('/your/path/to/a/dict/dump.txt') as handle:
    dictdump = json.loads(handle.read())
🌐
Python
docs.python.org › 3 › library › json.html
JSON encoder and decoder — Python 3.14.3 documentation
February 23, 2026 - fp (file-like object) – A .read()-supporting text file or binary file containing the JSON document to be deserialized. cls (a JSONDecoder subclass) – If set, a custom JSON decoder. Additional keyword arguments to load() will be passed to the constructor of cls. If None (the default), JSONDecoder is used. object_hook (callable | None) – If set, a function that is called with the result of any JSON object literal decoded (a dict).
Discussions

Deserialize a json string to an object in python - Stack Overflow
5 Can I deserialize Json to class like C# Newtonsoft in Python · 2 How to avoid hard-coding tons of dict key strings in Python More on stackoverflow.com
🌐 stackoverflow.com
Convert JSON string to dict using Python - Stack Overflow
I'm a little bit confused with JSON in Python. To me, it seems like a dictionary, and for that reason I'm trying to do that: More on stackoverflow.com
🌐 stackoverflow.com
How to turn JSON into objects in python?
It's easier (and probably better) if you define the class first. Then, turn the json into a dict, then into an instance of that class. import json class Person: def __init__(self, name, job): self.name = name self.job = job person_json = '''{ "name":"Harry", "job":"Mechanic" }''' person_dict = json.loads(person_json) person = Person(**person_dict) Edit: Sorry I didn't answer your exact question. But maybe that was still helpful. There's also attrdict . Making a whole class from a dict is certainly possible, but not something most people would want to do. And when you say "yield", do you mean you want the Person definition as Python code, or the Person class object? More on reddit.com
🌐 r/learnpython
8
2
September 2, 2021
De/Serializing JSON In Python, While Keeping Your Types
Why didn't pydantic work for you, and why not follow PEP8 with regards to tabs and spaces? More on reddit.com
🌐 r/Python
12
19
October 10, 2022
🌐
GeeksforGeeks
geeksforgeeks.org › deserialize-json-to-object-in-python
Deserialize JSON to Object in Python - GeeksforGeeks
July 7, 2021 - # importing the module import json # opening the JSON file data = open('file.json',) print("Datatype before deserialization : " + str(type(data))) # deserializing the data data = json.load(data) print("Datatype after deserialization : " + str(type(data))) ... In Python, class objects are used to organize complex information. To save or share this information, we need to convert it into a format like JSON, which is easy to read and write. Since class objects can't be saved directly as JSON, we first convert them into a dictionary (a data structure with ke
🌐
MojoAuth
mojoauth.com › serialize-and-deserialize › serialize-and-deserialize-json-with-python
Serialize and Deserialize JSON with Python | Serialize & Deserialize Data Across Languages
A common hurdle arises when you try to serialize custom Python objects. json.dumps() doesn't inherently know how to represent these. You'll need to either implement a custom JSON encoder or, more simply, convert your custom objects into dictionaries before serialization.
🌐
GeeksforGeeks
geeksforgeeks.org › python › serialize-and-deserialize-complex-json-in-python
Serialize and Deserialize complex JSON in Python - GeeksforGeeks
August 11, 2025 - json_data = json.dumps(team.__dict__, default=lambda o: o.__dict__, indent=4) Example: Here, we use default parameter to handle nested objects during serialization, then deserialize the JSON back to a Python object.
Find elsewhere
🌐
Medium
yuchen52.medium.com › serialize-and-deserialize-complex-json-in-python-205ecc636caa
Serialize and Deserialize complex JSON in Python | by Yuchen Z. | Medium
September 8, 2021 - Python and the json module is working extremely well with dictionaries. The following is for serializing and deserializing a Python dictionary:
🌐
Real Python
realpython.com › lessons › deserializing-json-data
Deserializing JSON Data (Video) – Real Python
We use this method when we’re reading in data from a file-like object. loads() will load JSON data from a string containing JSON-encoded data. Unless your encoded data is something very simple, these methods will most likely return a Python ...
Published   March 28, 2019
🌐
AskPython
askpython.com › home › serialize and deserialize json to objects in python
Serialize and Deserialize JSON to objects in Python - AskPython
July 5, 2021 - Post which, we pass the object referring the JSON file to the load() function and deserialize it into dictionary form. import json data = open('info.json',) op = json.load(data) print(op) print("Datatype after de-serialization : " + str(type(op))) ...
🌐
Python Examples
pythonexamples.org › python-json-to-dict
Python JSON to Dictionary
We will parse the JSON object to Dictionary, and access its values. import json jsonString = '{"a":54, "b": {"c":87}}' aDict = json.loads(jsonString) print(aDict) print(aDict['a']) print(aDict['b']) print(aDict['b']['c']) ... In this Python JSON Tutorial, we learned how to convert a JSON Object string to a Python Dictionary, with the help of well detailed example programs.
🌐
GeeksforGeeks
geeksforgeeks.org › python › convert-json-to-dictionary-in-python
Convert JSON to dictionary in Python - GeeksforGeeks
July 12, 2025 - Create a json string and store it in a variable 'json_string' after that we will convert the json string into dictionary by passing 'json_string' into json.loads() as argument and store the converted dictionary in 'json_dict'.
🌐
Reddit
reddit.com › r/python › de/serializing json in python, while keeping your types
r/Python on Reddit: De/Serializing JSON In Python, While Keeping Your Types
October 10, 2022 -

Short writeup of the motivations I had for writing a Python serialization library
https://medium.com/@steffen.cucos/de-serializing-json-in-python-4053366bc8ad
Coming from the world of Java I was used to dealing with external systems like DBs & APIs that communicate over varying messaging formats, but the details of how an object was sent or received over the wire was always hidden behind libraries that handled the process of turning a Java object into JSON & JSON back into a real Java object.

In Python it seems like the general approach to this serialization issue is to manually handle turning objects into JSON (hand written to_json, JSON.dumps(obj.__dict__ ), etc.), and to manually reconstruct an instance of an object for deserialization.

In a personal project of mine I ran into this issue on 2 fronts. Sending/Receiving data over an API, and saving/reading data from mongodb.

In order to solve the issue, I wrote a library called pserialization to automate the task of turning objects into JSON, and turning JSON back into an object.

The serialization part is actually fairly simple. Much like the JSON.dumps(obj.__dict__) approach, the library recursively serializes each field in an objects __dict__ attribute, and uses the type of each field to inform what JSON primitive to serialize into (int, float, bool, array, {}).

The deserialization part is more complicated, and requires you to tell the library what object you want to turn some JSON into, and to have type hints (either as a dataclass or in the __init__ of the object). Using the type information the library can know which types need to be instantiated and with which fields.

TLDR:
Upset that there is no generic way to convert from python objects to JSON and back, so wrote a library that uses type hints to automate the de/serialization process.

Source code:
https://github.com/SteffenCucos/PSerialization

🌐
PYnative
pynative.com › home › python › json › python convert json data into a custom python object
Python Convert JSON data Into a Custom Python Object – PYnative
May 14, 2021 - You know how to encode Python object into JSON. When you load JSON data from file or String using the json.load() and json.loads() method, it returns a dict. If we load JSON data directly into our custom type we can manipulate and use it more effortlessly. There are various ways to achieve this. You can pick the way you find it more useful for your problem. Let’s see how to deserialize a JSON string to a custom Python object.
🌐
Envato Tuts+
code.tutsplus.com › home › python
Serialization and Deserialization of Python Objects: Part 1 | Envato Tuts+
May 26, 2022 - The job of the custom encoder is to convert it to a Python object graph that the JSON encoder is able to encode. In this case, we have two objects that require special encoding: the datetime object and the A class. The following encoder does the job. Each special object is converted to a dict where the key is the name of the type surrounded by dunders (double underscores).
🌐
Real Python
realpython.com › python-json
Working With JSON Data in Python – Real Python
August 20, 2025 - The argument for the load() function must be either a text file or a binary file. The Python object that you get from json.load() depends on the top-level data type of your JSON file.