简体   繁体   English

如何将 JSON 的数据结构转换为 python 字典?

[英]How to convert this data structure of JSON to python dict?

I have parsed some JSON data to dict in python3, using json module.我已经使用 json 模块将一些 JSON 数据解析为 python3 中的 dict。

In the result dict, some data remains in the form of string, similar to 's:4:"name";s:5:"value";s:5:"array";a:4:{etc...}'结果dict中,部分数据以字符串形式保留,类似于's:4:"name";s:5:"value";s:5:"array";a:4:{etc... }'

What is the proper name of this, and how can I further convert to a dict, like {"name":"value", "array": [etc...]}这个的正确名称是什么,我怎样才能进一步转换为字典,比如 {"name":"value", "array": [etc...]}

One of the simplest ways is to use json :最简单的方法之一是使用json

import json


str_dict = "{'one': 'three', 'two': 'four'}"
new_dict = json.loads(str_dict)

Edit: You can also use ast :编辑:您也可以使用ast

import ast


srt_dict = "{'five': 'seven', 'six': 'eight'}"
new_dict = ast.literal_eval(str_dict)

Edit: You can also use eval() , however the docs recommend using literal_eval:编辑:您也可以使用eval() ,但是文档建议使用 literal_eval:

str_dict = "{'nine': 'ten', 'eleven': 'twelve'}"
new_dict = eval(str_dict)

There are more ways out there on the internet, however these are what I consider to be the simplest of them.互联网上有更多的方法,但这些是我认为最简单的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM