📌  相关文章
📜  Python|将字符串转换为 json 对象的方法

📅  最后修改于: 2022-05-13 01:55:30.357000             🧑  作者: Mango

Python|将字符串转换为 json 对象的方法

在许多 Web API 中,数据通常以字符串(JSON 对象)形式发送和获取,以使用该数据提取有意义的信息,我们需要将该数据转换为字典形式并用于进一步操作。

让我们看看一些将字符串转换为 json 的方法。方法 #1:使用json.loads将 dict 对象转换为字符串对象

# 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 

方法#2:使用eval() str 对象到 dict 对象

# Python code to demonstrate
# converting string to json 
# using eval
  
  
# inititialising json object string
ini_string = """{'nikhil': 1, 'akash' : 5,
            'manjeet' : 10, 'akshat' : 15}"""
  
# printing initial json
print ("initial 1st dictionary", ini_string)
print ("type of ini_object", type(ini_string))
  
# converting string to json
final_dictionary = eval(ini_string)
  
# printing final result
print ("final dictionary", str(final_dictionary))
print ("type of final_dictionary", type(final_dictionary))

输出:

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