将 Python 列表转换为 json 示例
Python有一个json 库,可以解析来自字符串或文件的JSON。该库将JSON解析为Python字典或列表。它还可以将Python字典或列表转换成JSON字符串。我们经常遇到这样的情况:我们需要从一个数据结构转换到另一个。
Python 有很多数据结构可以处理,每个结构都会增加一些东西。如果你正在使用API,我们就需要处理JSON数据。在本教程中,我们将看到如何将Python列表转换为JSON实例。
将Python列表转换为json
要在Python中把一个列表 转换为json,请使用json.dumps() 方法。json.dumps() 是一个内置函数,它接收一个列表作为参数并返回 json 值。json.dumps() 函数可以将任何数据类型如dict, str, int, float, bool,None转换为JSON。
但首先,你需要将json包导入你的程序中。然后,制作一个简单的列表,并编写json.dumps(list)。
请看下面的代码。
# app.py
import json
data = ["DisneyPlus", "Netflix", "Peacock"]
json_string = json.dumps(data)
print(json_string)
输出
➜ pyt python3 app.py
["DisneyPlus", "Netflix", "Peacock"]
➜ pyt
Pythonjson库可以解析来自字符串或文件的 JSON。该库将 JSON 解析为Python 字典或列表。它也可以将Python字典或列表转换为JSON字符串。
将JSON转换为Python对象(Dict)
要在Python中把json转换为一个字典,请使用json.load() 方法。 json.load() 是一个内置的Python方法,它接收一个json字符串作为参数并返回字典对象。
请看下面的代码。
# app.py
import json
json_data = '{"name": "Krunal", "city": "Rajkot"}'
python_obj = json.loads(json_data)
print(python_obj["name"])
print(python_obj["city"])
输出
➜ pyt python3 app.py
Krunal
Rajkot
➜ pyt
将JSON转换为Python对象 (列表)
要在Python中把JSON 转换为Python对象类型,请使用json.loads() 方法。json.load() 是一个内置的方法,它接收一个json字符串作为参数并返回Python对象。
请看下面的代码。
# app.py
import json
array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)
for element in data['drinks']:
print(element)
输出
➜ pyt python3 app.py
coffee
tea
water
➜ pyt
在Python中把JSON数据写到文件中。
要把一个json 数据 写入 文件,在 "w"模式下使用withopen()函数,然后使用json.dump() 方法写入文件中的所有内容。
好的,让我们来实现一个如何将JSON数据写入文件的程序。
请看下面的代码。
# app.py
import json
data = {"Eleven": "Millie",
"Mike": "Finn",
"Will": "Noah"}
with open('app.json', 'w') as f:
json.dump(data, f)
输出
在你的app.json 文件中,你有写好的数据json。
utf8-encode
如果我们想得到utf8-encoded,那么就写下面的代码。
# app.py
import json
data = {"Eleven": "Millie",
"Mike": "Finn",
"Will": "Noah"}
with open('app.json', 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=4)
以下缩进的输出将被写入文件中。
输出
{
"Eleven": "Millie",
"Mike": "Finn",
"Will": "Noah"
}
我们可以用下面的代码得到utf8编码的文件,而不是ascii编码的 。
# app.py
import json
data = {"Eleven": "Millie",
"Mike": "Finn",
"Will": "Noah"}
with open('app.json', 'w', encoding='utf-8') as f:
f.write(json.dumps(data, ensure_ascii=False))
输出
{"Eleven": "Millie", "Mike": "Finn", "Will": "Noah"}
在Windows上,open的encoding='utf-8′参数仍然是必要的。
我们可以避免在内存中存储数据的编码副本(转储的结果),要在Python 2和3中输出utf8编码的字节符,使用下面的代码。
import json, codecs
with open('app.txt', 'wb') as f:
json.dump(data, codecs.getwriter('utf-8')(f), ensure_ascii=False)
codecs.getwriter()函数的调用在Python 3中是多余的,但在Python 2中是必需的。
本教程就到此为止。
上一篇: 在 Vue 中实现 Excel 导入和导出功能(核心代码)
下一篇: JS 本地导出 CSV 文件