One way to avoid a copy is to reverse the list inplace, eg:

mylist.reverse()
json_string = json.dumps(mylist)

Then mylist.reverse() it back if needs be.

Answer from Jon Clements on Stack Overflow
Top answer
1 of 2
6

One way to avoid a copy is to reverse the list inplace, eg:

mylist.reverse()
json_string = json.dumps(mylist)

Then mylist.reverse() it back if needs be.

2 of 2
0

Before we go crazy, see if any of the following meet your performance requirements:

mylist.reverse(); json.dumps(mylist); mylist.reverse()
json.dumps(mylist[::-1])
json.dumps(tuple(reversed(mylist)))

You mentioned defining your own JSONEncoder default function, which is fairly simple to do (example at the very bottom*), but I don't think it works here since the json.JSONEncoder requires the default function to convert the object into one of the following:

None, True, False, str, int, float, list, tuple, dict

Converting an iterator to a list or tuple would create a large object, which is what we're trying to avoid.

You'll either need to modify your json library or monkey-patch it.

Here's the CPython source code of json.encoder. PyPy, Jython, and other Python implementations are probably using the same code for the json module.

https://github.com/python/cpython/blob/master/Lib/json/encoder.py#L204

def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
    _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
    ## HACK: hand-optimized bytecode; turn globals into locals
    ValueError=ValueError,
    dict=dict,
    float=float,
    id=id,
    int=int,
    isinstance=isinstance,
    list=list,
    str=str,
    tuple=tuple,
    _intstr=int.__str__,
    ...
    def _iterencode(o, _current_indent_level):
        if isinstance(o, str):
            yield _encoder(o)
        ...
        elif isinstance(o, (list, tuple)):
            yield from _iterencode_list(o, _current_indent_level)

        # Add support for processing iterators
        elif isinstance(o, iterator_types):
            # Side-effect: this will consume the iterator.
            # This is probably why it's not included in the official json module
            # We could use itertools.tee to be able to iterate over
            # the original iterator while still having an unconsumed iterator
            # but this would require updating all references to the original
            # iterator with the new unconsumed iterator.
            # The side effect may be unavoidable.
            yield from _iterencode_list(o, _current_index_level)

For performance reasons, you'll want to define the iterator types outside of the function and bring it in as a local.

str_iterator   = type(iter( str()    ))
list_iterator  = type(iter( list()   ))
tuple_iterator = type(iter( tuple()  ))
range_iterator = type(iter( range(0) ))
list_reverseiterator = type(reversed( list()  )) 
reverseiterator      = type(reversed( tuple() )) #same as <class 'reversed'>

# Add any other iterator classes that you need here, plus any container data types that json doesn't support (sets, frozensets, bytes, bytearray, array.array, numpy.array)
iterator_types = (str_iterator, list_iterator, tuple_iterator, range_iterator,
                  list_reverseiterator, reversed)

If you want to go the monkey-patching route, you'll need to redefine the json.encoder._make_iterencode function, replacing all occurrences of isinstance(X, (list, tuple)) with isinstance(X, (list, tuple)+iterator_types)

import json
def _make_iterencode(markers, _default, _encoder, _indent, _floatstr,
        _key_separator, _item_separator, _sort_keys, _skipkeys, _one_shot,
         iterable_types=_get_iterable_types(),
         ...
    ):
    ...

json.encoder._make_iterencode = _make_iterencode

These changes look something like this: https://github.com/python/cpython/pull/3034/files

*As promised, how to define your own default function, though not useful for dumping iterators without copying the iterator into a list or tuple first.

class JSONEncoderThatSupportsIterators(json.JSONEncoder):
    def default(self, o):
        try:
            iterable = iter(o)
        except TypeError:
            pass
        else:
            return list(iterable)
        # Let the base class default method raise the TypeError
        return json.JSONEncoder.default(self, o)

li = range(10000000) # or xrange if Python 2
dumped = JSONEncoderThatSupportsIterators().encode(reversed(li))
assert dumped.startswith('[999999, 999998, 999997, ')
assert dumped.endswith('6, 5, 4, 3, 2, 1, 0]')

Alternatively, rather than subclassing json.JSONEncoder, you can define the default(self, o) function and pass it as an argument to json.dumps(default=default).

🌐
Like Geeks
likegeeks.com › home › python › reverse json array in python: a comprehensive tutorial
Reverse JSON Array in Python: A Comprehensive Tutorial
Learn how to reverse JSON arrays in Python using reversed(), array.reverse(), list slicing, for loops, Pandas, NumPy, and custom functions.
Discussions

python - Iterating through a JSON object - Stack Overflow
# example of json data object group ... value for testdata in loadedjson['group']: print (accesscount['id']) # should print 2 then 3 if using test json · If you don't decode you will get bytes vs string errors in Python 3. ... wondering if your accesscount will punch out a error? I think testdata['id'] might make things work a little better in your final loop... More on stackoverflow.com
🌐 stackoverflow.com
python - How can I loop over entries in JSON? - Stack Overflow
I want to loop over the content of a JSON file and print it to the console. I think I did mix up something with lists. This is what I tried to get all the team_name elements from urllib2 import More on stackoverflow.com
🌐 stackoverflow.com
Using Python to loop through JSON dictionary that re-uses the same key?
To clarify, you're looking at the $ key right? - If this is the case, it looks like you can differentiate with the accompanying @id key. They seem to be consistent between the attribute structures e.g. it looks like the @id value 0x12d7f will consistently contain an IP in the paired $ key value . More on reddit.com
🌐 r/learnpython
5
3
October 13, 2022
Reverse loop an array of JSON data
I have a JSON array as { "Education": [ { "title": "Bachelor of Technology (B.Tech)", "current": false, "where": "Jawaharlal Nehru Technological University, Hyderabad", "from": 2007, "to": 2011 }, { "title": "Postgraduate Diploma in Computer and Information Sciences (PgDipCIS)", "current": ... More on discourse.gohugo.io
🌐 discourse.gohugo.io
1
0
November 5, 2018
🌐
Stack Overflow
stackoverflow.com › questions › 41231265 › using-python-to-read-through-a-directory-of-json-files-and-run-a-reversing-pytho
Using Python to read through a directory of JSON files and run a reversing Python script on each file - Stack Overflow
My approach is to use os.walk() on the Userss directory and carry out a reversing script which I have come up with on each file. My problem is actually iterating through the directory and reading the files in, in the first place. ... import os from operator import itemgetter, attrgetter, methodcaller import json rootdir = './Userss' fileHandles = {} count = 0 totalfilelines = 0 filenum = 0 lastName=None handle=None for files in os.walk(rootdir): #print files #print "---------" #print len(files) #for file in files: filenum += 1 with open(files) as infile: #for line in sortedpython(infile, key=itemgetter(2), reverse=True): for line in infile: ''' reversing script here '''
🌐
W3Schools
w3schools.com › python › ref_list_reverse.asp
Python List reverse() Method
Python Examples Python Compiler ... Q&A Python Bootcamp Python Certificate Python Training ... The reverse() method reverses the sorting order of the elements....
🌐
Python Forum
python-forum.io › thread-39669.html
Loop through json file and reset values [SOLVED]
March 23, 2023 - Hello everybody, I have a json file which stores information for different people, which looks like this: { 'person': [ { {'id': '1', 'name': 'Geroge' 'status': 'unsent' ...
🌐
Reddit
reddit.com › r/learnpython › using python to loop through json dictionary that re-uses the same key?
r/learnpython on Reddit: Using Python to loop through JSON dictionary that re-uses the same key?
October 13, 2022 -

I'm trying to restructure JSON output from a API to the specific format that Ansible wants for it's invetory file. To do this I thought I would loop through the JSON and grab the variables I need and then feed that into the proper structure. However, I noticed my API JSON is using the same $ key for multiple variables. How can I properly reference and differentiate between the variables? Here is an example:

 "model-responses": {
        "model": [
            {
                "@mh": "0x11e013",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch1"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "Raritan Computer, Inc.DV"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.1"
                    },
                    {
                        "@id": "0x10052",
                        "$": "PX2 030610"
                    }
                ]
            },
            {
                "@mh": "0x115014",
                "attribute": [
                    {
                        "@id": "0x1006e",
                        "$": "switch2"
                    },
                    {
                        "@id": "0x23000e",
                        "$": "DCS-7010T-48"
                    },
                    {
                        "@id": "0x12d7f",
                        "$": "10.10.10.2"
                    },
                    {
                        "@id": "0x10052",
                        "$": "Arista Networks EOS version 4.22.3M-INT running on an Arista Networks DCS-7010T-48"
                    }
                ]
            },
Find elsewhere
🌐
HUGO
discourse.gohugo.io › support
Reverse loop an array of JSON data - support - HUGO
November 5, 2018 - I have a JSON array as { "Education": [ { "title": "Bachelor of Technology (B.Tech)", "current": false, "where": "Jawaharlal Nehru Technological University, Hyderabad", "from": 2007, …
🌐
CodeRivers
coderivers.org › blog › python-reverse-loop-for
Python Reverse `for` Loop: A Comprehensive Guide - CodeRivers
January 29, 2025 - Python provides a built-in reversed() function that takes a sequence (like a list, tuple, or string) and returns a reverse iterator. This iterator can be used in a for loop to iterate over the sequence in reverse order.
🌐
GeeksforGeeks
geeksforgeeks.org › backward-iteration-in-python
Backward iteration in Python - GeeksforGeeks
November 20, 2024 - Python provides various methods for backward iteration, such as using negative indexing or employing built-in functions like reversed(). Use reversed() method when we simply need to loop backwards without modifying original sequence or there ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › loop-through-a-json-array-in-python
Loop through a JSON array in Python - GeeksforGeeks
July 23, 2025 - You can loop through a JSON array in Python by using the json module and then iterating through the array using a for loop.
🌐
ReqBin
reqbin.com › code › python › hcwbjlmi › python-reverse-string-example
How do I reverse a string in Python?
December 20, 2022 - While Python doesn't have a built-in method to reverse the string, there are several ways to do it with just a few lines of code. You can use the slicing operator, the reversed() and string.join() methods, reverse the string using a for loop or recursion. Or, you can easily implement your own string-reversing method. ... How do I post JSON using the Python Requests Library?
🌐
W3Schools
w3schools.com › python › python_json.asp
Python JSON
Remove List Duplicates Reverse a String Add Two Numbers · Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Bootcamp Python Certificate Python Training ... JSON is a syntax for storing and exchanging data.
🌐
Reddit
reddit.com › r/learnpython › efficient alternative for recursive for-loops while iterating large json?
r/learnpython on Reddit: Efficient alternative for recursive for-loops while iterating large JSON?
September 13, 2021 -

I got JSON files which can grow huge, I basically import it as a dictionary. My task is to process them in a certain way - for this purpose let's simplify my goal here:

  1. Iterate through the dictionary. Everytime i find a value, let's print 'Found a value: value'

  2. Everytime i find a list, print the key of that value then go back to step 1.

  3. Continue doing this until the entire dictionary has been navigated through.

Example and the current code I actively use:

iterThis = { 
            "a": "hello",
            "b": [{"name":"Bob"}, {"name":"Kate"}],
            "c": "world"
            }


def recursive(testDict):
    for key, value in testDict.items():
        if type(value) == list:
            print("Found a list: " + key)
            for l in value:
                recursive(l)
        else:
            print("Found a value: " + value

recursive(iterThis)

My expected output is the following:

Found a value: hello
Found a list: b
Found a value: Bob
Found a value: Kate
Found a value: world

This is a grand oversimplification of the overall task, but this is the most important part.

My problem is that the JSONs I have to process can grow huge (e.g. 20k rows), with lot of lists here and there, and there can be a list within a list within a list etc. This means that until the code reached the 'bottom', everything is pretty much held in memory and my intuition is that there should be a pythonistic approach to this that is efficient.

I have a vague intuition that suggests looking at two things: itertools and generators.

What do you think?

🌐
Reddit
reddit.com › r/learnpython › how do i loop through a nested object from a json file?
r/learnpython on Reddit: How do I loop through a nested object from a JSON file?
March 1, 2022 -

Hi there, I am trying to read through a package.json file which is below. I want to read in specifically the dependencies and add them to key, value variables. I can't figure out how to read in nested object. If anyone can give me any tips?

{
  "name": "untitled",
  "version": "0.1.0",
  "private": true,
  "dependencies": {
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "react-scripts": "5.0.0",
    "express": "https://github.com/IAmAndyIE/expressjs.com.git"
  },
}

My current code is below.

import json


def test_document():
    f = open('../untitled/package.json')

    data = json.load(f)

    for key, values in data.items():
        if key == "dependencies":
            print(values)

    f.close()


if __name__ == '__main__':
    test_document()

Thanks

Top answer
1 of 2
16

It's because of this line:

data = data['items'][0]

Here you have explicitly accessed that first item in each iteration of the loop.

Try this instead:

data = request.json()
items = data['items']

for item in items:
    price = item['salePrice']
    name = item['name']
    print(name)
2 of 2
4

Wim is right. Your problem comes from the fact that you are trying to manipulate JSON data when the data is not JSON ready yet.

Below is a cleaner version of your code which calls a fake API that returns a list of 10 users.

The code will only use 2 libraries:

  1. json: this library will make sure our data us JSON ready (for python, I should mention) before we can iterate through it
  2. requests: this library will allow us to perform the http request to get the data back

Using just these two libraries, I can get my data with requests, make it JSON ready using json, loop through it with python using the for ... in ... statement, and print the content any way I want, like so:

# importing the necessary libraries
import json
import requests

# Making the http request
r = requests.get('https://jsonplaceholder.typicode.com/users')

# Transforming the data returned into JSON format
data = r.json()

# Construct various objects and variables to read the data
one_user = {}    
first_user = data[0]
first_user_name = data[0]['name']

print('The first user is:', first_user)
print('\n')
print('The first user s name is:', first_user_name)
print('\n')

for user in data:
    one_user['name'] = user['name']
    one_user['email'] = user['email']
    one_user['phone'] = user['phone']
    print(one_user)
    print('\n')

Data Sample

[
    {
        "id": 1,
        "name": "Leanne Graham",
        "username": "Bret",
        "email": "[email protected]",
        "address": {
        "street": "Kulas Light",
        "suite": "Apt. 556",
        "city": "Gwenborough",
        "zipcode": "92998-3874",
        "geo": {
            "lat": "-37.3159",
            "lng": "81.1496"
        }
        },
        "phone": "1-770-736-8031 x56442",
        "website": "hildegard.org",
        "company": {
            "name": "Romaguera-Crona",
            "catchPhrase": "Multi-layered client-server neural-net",
            "bs": "harness real-time e-markets"
        }
    },
    {...}
]

Screenshot of a working example on jupyter notebook

I hope this helps someone out there trying to solve this issue the right way.

🌐
Devsheet
devsheet.com › reverse-a-list-items-in-python
Reverse a list items in Python - Devsheet
To reverse the order of all the items of a list in Python, you can use List.reverse() function. Below is the code
🌐
Python Morsels
pythonmorsels.com › looping-in-reverse
Looping in reverse - Python Morsels
May 27, 2025 - To loop in the reverse direction, you can use Python's built-in reversed function: >>> colors = ["purple", "blue", "green", "pink", "red"] >>> for color in reversed(colors): ... print("I like", color) ...