深度阅读

python中字符串转换成json

作者
作者
2023年08月22日
更新时间
10.83 分钟
阅读时间
0
阅读量

通过eval

eval() 函数用来执行一个字符串表达式,并返回表达式的值。

通过eval可以把list,tuple,dict和string相互转化

# Python code to demonstrate
# converting string to json
# using json.loads
import json

# inititialising json object
ini_string = {'nikhil': 1, 'akash' : 5,
            'manjeet' : 10, 'akshat' : 15}

# printing initial json
ini_string = json.dumps(ini_string)
print ("initial 1st dictionary", ini_string)
print ("type of ini_object", type(ini_string))

# converting string to json
final_dictionary = json.loads(ini_string)

# printing final result
print ("final dictionary", str(final_dictionary))
print ("type of final_dictionary", type(final_dictionary))

initial 1st dictionary {'manjeet': 10, 'nikhil': 1, 'akshat': 15, 'akash': 5}
type of ini_object 
final dictionary {'nikhil': 1, 'manjeet': 10, 'akshat': 15, 'akash': 5}
type of final\_dictionary 

出处
https://www.geeksforgeeks.org/python-ways-to-convert-string-to-json-object/

literal_eval

参考地址
https://www.jianshu.com/p/9dc06b7f642b

eval更多用法
https://realpython.com/python-eval-function/

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。