Python Forum

Full Version: Convert string to JSON using a for loop
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I need to transform a string like "Name1:Val1|Name2:Val2" to a JSON like [{'name': 'Name1', 'value': 'Val1', 'status': 'Passed'}, {'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}].
When I run my code the result is [{'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}, {'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}].
I get {'name': 'Name1', 'value': 'Val1', 'status': 'Passed'} from the first loop execution. But it the second loop it is replaced by {'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}.

My code is:

import json

group={}
tests=[]
currentdata={}

str="Name1:Val1|Name2:Val2"

print(str)
print("------------------------------")

splitstr=str.split("|")
print(splitstr)
print("------------------------------")

for dataset in splitstr:
    data=dataset.split(":")
    currentdata["name"]=data[0]
    currentdata["value"]=data[1]
    currentdata["status"]="Passed"
    tests.append(currentdata)
    
    print(data)
    print(data[0])
    print(data[1])
    print(currentdata)
    print(tests)
    print("------------------------------")
The output is:
Output:
Name1:Val1|Name2:Val2 ------------------------------ ['Name1:Val1', 'Name2:Val2'] ------------------------------ ['Name1', 'Val1'] Name1 Val1 {'name': 'Name1', 'value': 'Val1', 'status': 'Passed'} [{'name': 'Name1', 'value': 'Val1', 'status': 'Passed'}] ------------------------------ ['Name2', 'Val2'] Name2 Val2 {'name': 'Name2', 'value': 'Val2', 'status': 'Passed'} [{'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}, {'name': 'Name2', 'value': 'Val2', 'status': 'Passed'}]
------------------------------

Thanks for your help.
Thank you, I will do it properly next time.
dict is mutable object. You define currentdata before the loop. Basically you add same object multiple times. When you change value for particular key inside the loop, it change all objects inside the dict.
move line 5 inside the loop.

Also, don't use str as name, it's a built-in function.
Many thanks, buran, for fixing this beginner issue.