0

I have a python object which I dump to json and write to a file.

results = [
{'destination': (x,y), 'id': 'dsss', 'origin': (x,r), 'waypoints': [[s,l],[d,s]]},
{'destination': (x1, y1), 'id': 'ddsdsee', 'origin': (z,f), 'waypoints': [[e,y],[d,e]]}]

with gzip.open("test.json.gz",'w') as outfile:
    json.dump(results,outfile,indent=2)

I then open the file elsewhere, via:

schedule_f = gzip.open("test.json.gz")
schedule = json.load(schedule_f)

pprint(schedule[0]) return:

{'destination': [x,y], 'id': 'dsss', 'origin': [x,r], 'waypoints': [[s,l],[d,s]]

Why are origin and destination fields converted to a list? I clearly specified ( and not [

1
  • Your input is not valid Python, the first item in results is missing a closing }. Commented Dec 5, 2016 at 9:02

6 Answers 6

1

JSON doesn't have any concept of tuples: only arrays, which map to Python lists.

There is no difference from a practical point of view, but if you think you really really need tuples, you will have to convert them yourself

Sign up to request clarification or add additional context in comments.

Comments

1

Nested Python objects can be complexer than you are are allowed to store in JSON format. JSON format does only have a container and its parsed as list when you import it into Python.

Such format conversion are not conservative, they destroy informations. You will not be able to store datetime too, it will be casted to string.

Comments

1

JSON does not support tuples, so the json module converts them to arrays, which are supported by JSON.

Comments

1

JSON does not know the "(" (it is not specified in the JSON notation).

Your json.dump intelligently converts it to a list.

Comments

0

Please, read what JSON is: https://en.wikipedia.org/wiki/JSON

JSON doesn't support tuple datatype. It supports list only, that's why Python tuples were converted into JSON lists.

Comments

0

If you want the dump and load object exactly same then use pickle module instead of json module.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.