I use the following code to get json from the string value, update it and return back as string (simplejson
is used):
if text:
qj = json.loads(text)
else:
qj = json.loads('{}')
if not qj.get(counter):
qj[counter] = {}
if not qj.get(counter).get('values'):
qj[counter]['values'] = []
if not value in qj[counter]['values']: # avoid duplicates
qj[counter]['values'].append(value)
text = json.dumps(qj)
Why do I get the following result if I run the function with the same counter
value several times (4
in the example below):
{"4": {"values": ["test1"]}, "4": {"values": ["test2"]}}
The number of created 4
sections is always 2. If I run the function 3rd time, then first value is updated (not added as I expect).
The expect output should be:
{"4": {"values": ["test1", "test2", "test3"]}}
What is wrong in my code?
If in your first pass you have following json:
{4: {"values": ["test1"]}}
You will have this string after text = json.dumps(qj)
:
'{"4": {"values": ["test1"]}}'
Now, when loading the json with qj = json.loads(text)
, you receive:
{'4': {'values': ['test1']}} # 4 has turned to '4'!
Your check if 4
already exists, fails because it is a number.
So to solve your problem, you can simply turn the counter into a string during the test:
if not qj.get(str(counter)):
...
The reason for this behaviour is that json does not allow integers as keys, see the definition of a pair in the JSON documentation:
pair
string : value