Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

Convert from Dict to JSON in Python

I want to construct a dict in Python which with json.dumps(arg) will convert to the following JSON structure:

"{"type":"id",
"entries:":
[["a",91],
["b",65],
["c",26],
["d",25]]}"

This is what I have so far:

json_dict = {'type': str("id"),
            'entries': [['a': "91"], #Error line
                        ['b': "65"],
                        ['c': "26"],
                        ['d': "25"]]}

I am getting "invalid syntax" error on the line which is marked with #Error line. How can I represent this hierarchical structure in a dict and still be able to convert it to the desired JSON structure?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Python lists use commas, not colons:

json_dict = {'type': str("id"),
            'entries': [['a', "91"],  # note the comma after 'a', not a colon
                        ['b', "65"],
                        ['c', "26"],
                        ['d', "25"]]}

With commas, this is now valid Python syntax, producing a data structure that can be serialised to JSON:

>>> json_dict = {'type': str("id"),
...             'entries': [['a', "91"],
...                         ['b', "65"],
...                         ['c', "26"],
...                         ['d', "25"]]}
>>> import json
>>> json.dumps(json_dict)
'{"type": "id", "entries": [["a", "91"], ["b", "65"], ["c", "26"], ["d", "25"]]}'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...