📜  Python – 元组字典到 JSON

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

Python – 元组字典到 JSON

在本文中,我们将讨论如何将元组字典转换为 JSON。

方法一:使用 json.dumps()

这会将元组字典转换为 json

示例:元组到 json 转换的Python字典

Python3
# import json module
import json
  
# dictionary of employee data
data = {
    "id": ("1", "2", "3"),
    "name": ("bhanu", "sivanagulu"),
    "department": ("HR", "IT")
}
  
# convert into json
final = json.dumps(data, indent=2)
  
# display
print(final)


Python3
# import json module
from google.colab import files
import json
  
# dictionary of employee data
data = {
    "id": ("1", "2", "3"),
    "name": ("bhanu", "sivanagulu"),
    "department": ("HR", "IT")
}
  
# convert into json
# file name is mydata
with open("mydata.json", "w") as final:
    json.dump(data, final)
  
# download the json file
files.download('mydata.json')


输出

{
  "id": [
    "1",
    "2",
    "3"
  ],
  "name": [
    "bhanu",
    "sivanagulu"
  ],
  "department": [
    "HR",
    "IT"
  ]
}

方法二:使用 json.dump()

这会将转换后的 json 数据写入文件,该文件将被下载并保存在您的计算机上。

语法

with open("mydata.json", "w") as final:
    json.dump(data, final)

其中,mydata 是新的 JSON 文件

最后,我们必须下载创建的 JSON 文件

语法

files.download('mydata.json')

示例:元组到 json 转换的Python字典

Python3

# import json module
from google.colab import files
import json
  
# dictionary of employee data
data = {
    "id": ("1", "2", "3"),
    "name": ("bhanu", "sivanagulu"),
    "department": ("HR", "IT")
}
  
# convert into json
# file name is mydata
with open("mydata.json", "w") as final:
    json.dump(data, final)
  
# download the json file
files.download('mydata.json')

输出: