Search code examples
pythonjsongenerate

generate JSON file content


I am a beginner with JSON.

I have the following in my JSON file (file-1) :

{
    "Aps": [
      {
            "type": "opo",
            "price_min": 7,
            "price_max":10,
            "app_time": 0,
           
            "arguments": {
                "prices": 15,
                "apps_num": "112"
            },
            "attributes": {
            "name":"user1",
            "priority":"100"
            
            } 
    }
}

How write python code that generates another JSON file that contain the same content of file-1 but duplicated 100 time in each time the name of user is different user2, user3 ... user100 and also it's priority.

I have tried the following but it is not working :


for lp in range(100):
    with open("sample.json", "w") as outfile:
        outfile.write(json_object)

but it is not working ..

the required output is as follow :

{
    "Aps": [
      {
            "type": "opo",
            "price_min": 7,
            "price_max":10,
            "app_time": 0,
           
            "arguments": {
                "prices": 15,
                "apps_num": "112"
            },
            "attributes": {
            "name":"user1",
            "priority":"100"
            
            } 
    }, 
      {
            "type": "opo",
            "price_min": 7,
            "price_max":10,
            "app_time": 0,
           
            "arguments": {
                "prices": 15,
                "apps_num": "112"
            },
            "attributes": {
            "name":"user2",
            "priority":"90"
            
            } 
    },
   {
            "type": "opo",
            "price_min": 7,
            "price_max":10,
            "app_time": 0,
           
            "arguments": {
                "prices": 15,
                "apps_num": "112"
            },
            "attributes": {
            "name":"user2",
            "priority":"80"
            
            } 
    },
..............

}

Solution

  • I made a little code here using json and copy module

    json for reading and writing json files

    copy because I had some trouble with reference variables see documentation for copy; if I changed 'temp' dict then it would affect all occurrences in 'file' dict

    import json
    import copy
    
    repeats = 100
    file = json.loads(open('file.json', 'r').read())
    temp1 = json.loads(open('file.json', 'r').read())['Aps'][0]
    for repeat in range(repeats):
        temp = copy.deepcopy(temp1)
        temp['attributes']['name'] = f"user{repeat + 2}"
        temp['attributes']['priority'] = f"{repeat*10+100 - repeat*20}"
        file['Aps'].append(temp)
        temp1 = copy.deepcopy(temp)
    json.dump(file, open('file1.json', 'w'), indent=4)