This question clearly explains how to send a response using json and python dicts. The example however uses String as the value type in this dict. How would one do this with dict as value type? That is a dict with with dict as a value.
Asked
Active
Viewed 516 times
0
-
I wasn't specific enough. The specific type of dict I was referring to had a tuple as a key: json.dumps({'foo': {('bar','baz'): 42}}) results in "TypeError: keys must be a string" – lf215 Dec 30 '13 at 05:52
-
A Key of dictionary cannot be tuple `('bar', 'baz')` is invalid. – adityasdarma1 Dec 30 '13 at 06:21
2 Answers
1
By giving it a dict with a dict as a value type.
>>> json.dumps({'foo': {'bar': 42}})
'{"foo": {"bar": 42}}'

Ignacio Vazquez-Abrams
- 776,304
- 153
- 1,341
- 1,358
1
To clarify adityasdarma1's comment: this is not a limitation of Python or Django, but of JSON. In JSON, object keys must always be strings. There is no "tuple" type in JSON or JavaScript anyway; and arrays can't be keys because they are mutable. (In Python, tuples can be dict keys, but lists can't.)
I'm not sure why you would need that, though. You can either concatenate the values in some way to make a string key - eg "bar-baz"
- or alternatively you might need a more complex nested structure, with bar
as the key of the outer dict and baz
as an inner one. Without seeing your full data structure, it's hard to advise further.

Daniel Roseman
- 588,541
- 66
- 880
- 895