Python - 将字符串转换为 json 对象的方法
pythonserver side programmingprogramming更新于 2025/9/17 6:36:17
在许多 Web API 中,数据通常以字典(JSON 对象)形式的字符串发送和获取,为了使用该数据提取有意义的信息,我们需要将该数据转换为字典形式并用于进一步的操作。
示例
# 将字符串转换为 json
# 使用 json.loads
import json
# 初始化 json 对象
ini_string = {'vishesh': 1, 'ram' : 5, 'prashant' : 10, 'vishal' : 15}
# 打印初始 json
ini_string = json.dumps(ini_string)
print ("initial 1st dictionary", ini_string)
print ("type of ini_object", type(ini_string))
# 将字符串转换为 json
final_dictionary = json.loads(ini_string)
# 打印最终结果
print ("final dictionary", str(final_dictionary))
print ("type of final_dictionary", type(final_dictionary))
输出
('initial 1st dictionary', '{"vishal": 15, "ram": 5, "vishesh": 1, "prashant": 10}')
('type of ini_object', <type 'str'>)
('final dictionary', "{u'vishal': 15, u'ram': 5, u'vishesh': 1, u'prashant': 10}")
('type of final_dictionary', <type 'dict'>)
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

