Split a JSON File into Separate Files in Python

Split a JSON File into Separate Files in Python

  • Python
  • 1 min read

This tutorial shows how you can split a JSON file into separate files in Python.

Example: Splitting a JSON file into Separate Files in Python

In the below example, it will split the JSON file using the Python piping system:

  • The code starts by importing the JSON module.
  • It then creates a variable called data and loads it with the contents of yourJSONArrayFile.json using the load() function from the json module.
  • The code then iterates through each item in the data, creating a new file for each iteration (i).
  • The code opens up str(i) + '.json' as f_out and dumps x into that file using dump().
  • The code will create a file called "yourJSONArrayFile.json" that contains the data from yourJSONArrayFile.json
import json

with open('yourJSONArrayFile.json') as f:
  data = json.load(f)
  for i, x in enumerate(data):
    with open(str(i) + '.json', 'w') as f_out:
      json.dump(x, f_out)

See also: