Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
For data = {"p": (1, 2), 3: "x", "t": {"a"}}, say what json.dumps(data) does, and what you must change so that it works. Then say what json.loads gives back for the fixed data.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Look at each part: is it a kind of value that JSON keeps?
"p": (1, 2): a tuple. JSON has no tuples, but dumps accepts it and writes a list.3: "x": a number key. dumps accepts it and writes the key as the text "3"."t": {"a"}: a set. dumps raises a TypeError: a set cannot be saved.The fix. Change the set into a list before saving.
Check. The text is {"p": [1, 2], "3": "x", "t": ["a"]}. Loading gives {'p': [1, 2], '3': 'x', 't': ['a']}: the tuple is a list, and the key is a text. So back == data is False.
Answer: The set raises a TypeError. After the fix, the tuple comes back as a list and the number key as a text.
Log in to join the discussion.
Loading…