Joseph Wahba Joseph Wahba - 16 days ago 10
JSON Question

Python append json to json list

Hi there I'm trying to append JSON objects to form a list of JSON objects to form a list.

def GenIndentifier(options):
data=json.dumps([identifier,hex_dig])
return data


data here is a valid JSON object as follows:

["27780741708467800000001", "e5073922dbb7a278769d52277d49c6ad3017b1ba"]


Afterwards, I loop through the GenIdentifier function to generate many JSON objects

data=[]
for i in range(0,2,1):
...
data.append(GenIndentifier(options))
print data


Now the list of JSON data is not a valid JSON format because of some single quotations that pop up

['["27780741708467800000000", "f798d2cd9aec1b98fb48b34fd249fe19c06a4a1d"]', '["27780741708467800000001", "e5073922dbb7a278769d52277d49c6ad3017b1ba"]']


Any idea how to solve that? I've searched and googled but no luck.

Answer

The trouble is that you are dumping your data to JSON inside GenIndentifier, then appending that JSON string to a list.

Instead you should move the JSON conversion out of that function, and do it at the end:

def GenIndentifier(options):
    data = [identifier, hex_dig]
    return data

data = []
for i in range(0, 2, 1):
    ...
    data.append(GenIndentifier(options))
data = json.dumps(data)
print data
Comments