Reputation:
I have a highscore that as the structure like this:
[(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]
and I need to get the JSON format for it like this :
{"Test":300, "Test1":400.....}
But how hard I try I only get results like this :
[["Test":300],["Test1":400],....]
How can I get the json format right? I am using json.dumps(highscore) also tried son.dumps({highscore})
Upvotes: 4
Views: 523
Reputation: 6819
Convert the list of tuples to a dictionary first before passing it to json.dumps()
.
import json
a = [(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]
rs = json.dumps(dict(a))
print(rs)
>>>{"300": "Test2", "400": "Test1", "500": "Test2", "600": "Test2", "5": "Test2", "100": "Test2"}
Edit:
If you want to swap the keys and values in the json object you can just swap the tuple positions first but then you would only be able to keep a single instance of each key-value pair as a dictionary can only keep unique keys.
a = [(300, 'Test'), (400, 'Test1'), (500, 'Test2'), (500, 'Test2'), (600, 'Test2'), (5, 'Test2'), (500, 'Test2'), (600, 'Test2'), (300, 'Test2'), (100, 'Test2')]
swap = [(y,x) for x,y in a]
res = json.dumps(dict(swap))
print(res)
>>>{"Test": 300, "Test1": 400, "Test2": 100}
Upvotes: 3
Reputation: 51
do you try to use JSON.parse()?
JSON.parse(json);
check this code, may be solved your problem.
Upvotes: 0