1

I want to generate json file.

My steps are:

  1. setup configuration using lists
  2. loop and build dictionary
  3. append dictionary to list
  4. save list as json

I can replicate issue using snippet below:

import json 

myList = ['a', 'b', 'c']
number = 1
jsonList = list()
jsonDict = dict()

for name in myList:

    jsonDict["key"] =  "Value:" + str(number)
    jsonDict["Letter"] =  "Letter:" + str(name)
    print(jsonDict)
    jsonList.append(jsonDict)        
    number = number + 1


print(json.dumps(jsonList))

Issue: jsonDict has correct values such as I planned:

{'key': 'Value:1', 'Letter': 'Letter:a'} 
{'key': 'Value:2', 'Letter': 'Letter:b'} 
{'key': 'Value:3', 'Letter': 'Letter:c'}

However after converting list to json string it becomes:

[{"key": "Value:3", "Letter": "Letter:c"}, 
{"key": "Value:3", "Letter": "Letter:c"}, 
{"key": "Value:3", "Letter": "Letter:c"}]
BI Dude
  • 1,842
  • 5
  • 37
  • 67

0 Answers0