Skip to content
Advertisement

Python code to multiple JSON files with different names

I’m new to python and programming in general, asking for help: What to run in python code to print this data in multiple JSON files (300 files) that every file change the “name” line from #1 to #300 and the JSON files names will be like from 1.json to 300.json is it possible?

{
  "description": "#", 
  "image": "#", 
  "name": "#1",
  "attributes": [
    {
      "trait_type": "#", 
      "value": "#"
    } 
    ] 
}

Advertisement

Answer

try this:

# library to work with json stuff
import json

# you can create dict first represent the json
json_dict = {
  "description": "#", 
  "image": "#", 
  "name": "#1",
  "attributes": [
    {
      "trait_type": "#", 
      "value": "#"
    } 
    ] 
}

# define numbers of file you want to create
n = 300
for i in range(1, n+1):
    # change the "name" atribute for every iteration
    # you can use f-string method
    json_dict["name"] = f"#{i}"

    # save the dict to file
    # again, use the f-string to name the file
    with open(f"{i}.json", 'w') as json_file:
        #json.dump() method save dict json to file
        json.dump(json_dict, json_file)
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement