Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
322 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 Reply

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"]]}'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...