I have a Sample JSON record in a file as below
{ "name":"John", "age":30, "car":"BMW" }
I want to create more JSON records out of it and i want to minimize the i/o by not writing to the file system everytime i create sample record, the code below is to change the age using parameters and hold the JSON records in a list and write to the file system when i am done generating the records.
The output looks like
[{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }]
$$$ the issue i see is, when i write myOutput list it generates 4 records in it but all of them are duplicates, the last json that was produced is written to the whole list. Instead i am looking for something like below
[{ "name":"John", "age":1, "car":"BMW" }
{ "name":"John", "age":2, "car":"BMW" }
{ "name":"John", "age":3, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }]
###################################################################################################################
{ "name":"John", "age":30, "car":"BMW" }
I want to create more JSON records out of it and i want to minimize the i/o by not writing to the file system everytime i create sample record, the code below is to change the age using parameters and hold the JSON records in a list and write to the file system when i am done generating the records.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# Read the sample file with open ( "C:/myfile.json" ) as file : originalJSON = json.load( file ) # How many sample Records? numberOfRecords = 4 i = 1 myOutput = [] # initializing a dummy list to append my json's while (i < = numberOfRecords): # Change the age originalJSON[ "age" ] = i myOutput.append(originalJSON) i + = 1 # After appending all the JSON's to the list i want to write the JSON array to a file with open ( "C:/multiplerecords.json" , 'w' ) as multipleJsons: json.dump(myOutput, multipleJsons) |
[{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }]
$$$ the issue i see is, when i write myOutput list it generates 4 records in it but all of them are duplicates, the last json that was produced is written to the whole list. Instead i am looking for something like below
[{ "name":"John", "age":1, "car":"BMW" }
{ "name":"John", "age":2, "car":"BMW" }
{ "name":"John", "age":3, "car":"BMW" }
{ "name":"John", "age":4, "car":"BMW" }]
###################################################################################################################