首页 > 编程知识 正文

在 Python 中将字符串转换为 JSON

时间:2023-11-26 13:13:10 阅读:309352 作者:HZZY

在深入探讨这个话题之前,让我们先来看一下什么是字符串,什么是 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'>

说明:

是时候看到解释了,这样我们的逻辑就变得清晰了-

  1. 由于这里的目标是将字符串转换为 json 文件,我们将首先导入 json 模块。
  2. 下一步是初始化 json 对象,在该对象中,我们将主题名称作为键,然后指定它们对应的值。
  3. 之后,我们使用转储()将 Python 对象转换为 json 字符串。
  4. 最后,我们将使用 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'>

说明:

让我们了解一下我们在上面的程序中做了什么。

  1. 由于这里的目标是将字符串转换为 json 文件,我们将首先导入 json 模块。
  2. 下一步是初始化 json 对象,在该对象中,我们将主题名称作为键,然后指定它们对应的值。
  3. 之后,我们使用 eval() 将一个 Python 字符串转换为 json。
  4. 在执行程序时,它会显示所需的输出。

正在获取值

最后,在最后一个程序中,我们将在字符串转换为 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

我们可以在输出中观察到以下情况-

  1. 我们已经使用 json.loads()将字符串转换为 json。
  2. 在此之后,我们使用键“C_code”和“Java_code”来获取它们相应的值。

结论

在本教程中,我们学习了如何使用 Python 将字符串转换为 json。


版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。