2

I have a tuple (could also use list instead) like this:

 (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')

What would be a sensible way to represent this as a JSON struct in python? The key is a string like so:

 { 
    "John Smith" : (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-') 
 }

Any suggestions? The JSON will be parsed in JS in the front end and will always be the same length. Missing entries are represented by '-'.

2
  • Have a look at json.dumps Commented Dec 16, 2015 at 4:48
  • Is the problem that you don't know how to turn that dict into a string representing the JSON? Commented Dec 16, 2015 at 4:48

2 Answers 2

1

Use json.dumps.

>>> import json
>>> data = (1, 'jsmith', 'Ferrari', '10 million', 39, 16, 2, 0, '-')
>>> json.dumps({'John Smith': data})
'{"John Smith": [1, "jsmith", "Ferrari", "10 million", 39, 16, 2, 0, "-"]}'

BTW, JSON has only array ([...]); no distinction between list and tuple.

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

Comments

1

Represent a list as an array, i.e. beginning with [ and ending with ].

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.