开发 / 默认 · 3月 8, 2022 0

python中字符串转换成json

内容纲要

通过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/

%d 博主赞过: