Python教程-在Python中将字符串转换为JSON
            
            在深入研究这个主题之前,让我们先了解一下什么是字符串和JSON。
字符串: 是由用单引号 '' 标记的字符序列。它们是不可变的,这意味着一旦声明就无法更改。
JSON: 代表 "JavaScript对象表示法",JSON文件由文本组成,可以轻松被人类阅读,并以属性-值对的形式存在。
JSON文件的扩展名是 ".json"
让我们来看一下在Python中将字符串转换为JSON的第一种方法。
以下程序说明了相同的内容。
# converting string to json  
import json  
  
# initialize the json object  
i_string = {'C_code': 1, 'C++_code' : 26,  
      'Java_code' : 17, 'Python_code' : 28}  
  
# printing initial json  
i_string = json.dumps(i_string)  
print ("The declared dictionary is ", i_string)  
print ("It's type is ", type(i_string))  
  
# converting string to json  
res_dictionary = json.loads(i_string)  
  
# printing the final result  
print ("The resultant dictionary is ", str(res_dictionary))  
print ("The type of resultant dictionary is", type(res_dictionary))  输出:
The declared dictionary is {'C_code': 1, 'C++_code' : 26,
      'Java_code' : 17, 'Python_code' : 28}
It's type is <class 'str'>
The resultant dictionary is {'C_code': 1, 'C++_code' : 26,
      'Java_code' : 17, 'Python_code' : 28}
The type of resultant dictionary is <class 'dict'>解释:
现在是时候看解释,以便我们的逻辑变得清晰-
- 由于这里的目标是将字符串转换为JSON文件,我们首先导入了json模块。
 - 接下来的步骤是初始化JSON对象,在其中我们将科目名称作为键,然后指定它们的对应值。
 - 然后,我们使用 dumps() 将Python对象转换为JSON字符串。
 - 最后,我们将使用 loads() 解析JSON字符串并将其转换为字典。
 
使用 eval()
# converting string to json  
import json  
  
# initialize the json object  
i_string = """ {'C_code': 1, 'C++_code' : 26,  
      'Java_code' : 17, 'Python_code' : 28}  
"""  
  
# printing initial json  
print ("The declared dictionary is ", i_string)  
print ("Its type is ", type(i_string))  
  
# converting string to json  
res_dictionary = eval(i_string)  
  
# printing the final result  
print ("The resultant dictionary is ", str(res_dictionary))  
print ("The type of resultant dictionary is ", type(res_dictionary))  输出:
The declared dictionary is   {'C_code': 1, 'C++_code' : 26,
            'Java_code' : 17, 'Python_code' : 28}
Its type is  <class 'str'>
The resultant dictionary is  {'C_code': 1, 'C++_code': 26, 'Java_code': 17, 'Python_code': 28}
The type of resultant dictionary is  <class 'dict'>解释:
让我们了解一下上面程序中所做的事情。
- 由于这里的目标是将字符串转换为JSON文件,我们首先导入了json模块。
 - 接下来的步骤是初始化JSON对象,在其中我们将科目名称作为键,然后指定它们的对应值。
 - 然后,我们使用 eval() 将Python字符串转换为JSON。
 - 执行程序后,它显示所需的输出。
 
获取值
最后,在最后一个程序中,我们将在将字符串转换为JSON后获取值。
让我们来看看它。
import json  
i_dict = '{"C_code": 1, "C++_code" : 26, "Java_code":17, "Python_code":28}'  
res = json.loads(i_dict)  
print(res["C_code"])  
print(res["Java_code"])  输出:
1
17我们可以观察输出中的以下内容-
- 我们使用json.loads()将字符串转换为JSON。
 - 在此之后,我们使用键 "C_code" 和 "Java_code" 获取它们对应的值。
 
结论
在本教程中,我们学习了如何使用Python将字符串转换为JSON。