Search code examples
pythoniosjsonpython-3.xmacos-sierra

Python script for create multiple JSON files with predefined data


I'm new to Python, I have simple requirement in my iOS project. I want to create multiple JSON files with some fix data in each file. I googled some articles but didn't found exactly what I wish to do. So how do I achieve this?

Following things I'm able to do this but not giving expected output:

I have txt file which has list of 100 names, This text file I have kept in folder which has script file also, Now I want to create txt file for each name in the list in the same folder for that I have did something like this:

titles = open("title.txt",'r')

for lines in titles:
    output = open((lines.strip())+'.json','w')
    output.write(lines.strip('\n'))
    output.close()

titles.close()

This script creating files of mentioned names successfully.

Now I want to write predefined some fix data in each file. This is my sample json data, I want to copy this data into each file. How do I achieve this.

{
  "product": "Live JSON generator",
  "version": 3.1,
  "releaseDate": "2014-06-25T00:00:00.000Z",
  "demo": true,
  "person": {
    "id": 12345,
    "name": "John Doe",
    "phones": {
      "home": "800-123-4567",
      "mobile": "877-123-1234"
    },
    "email": [
      "jd@example.com",
      "jd@example.org"
    ],
    "dateOfBirth": "1980-01-02T00:00:00.000Z",
    "registered": true,
    "emergencyContacts": [
      {
        "name": "Jane Doe",
        "phone": "888-555-1212",
        "relationship": "spouse"
      },
      {
        "name": "Justin Doe",
        "phone": "877-123-1212",
        "relationship": "parent"
      }
    ]
  }
}

Solution

  • You can use pprint to print the data in the file. If you want you can also modify the json dict and store it as you like. Here is a quick example -

    import pprint
    my_json_dict = {'some': 'data'}
    titles = open("title.txt",'r')
    
    for title in titles:
        output = open((title.strip())+'.json','w')
        pprint.pprint(my_json_dict, stream=output, indent=2)
        output.close()
    
    titles.close()