溫馨提示×

python怎么生成json數據

小億
259
2023-08-16 10:08:48
欄目: 編程語言

生成json數據有多種方法,以下是其中幾種常用的方法:

  1. 使用Python的json模塊:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
  1. 使用Python的字典(dict)對象轉換為json字符串:
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = str(data).replace("'", '"')
print(json_data)
  1. 使用Python的pandas庫將數據框(DataFrame)對象轉換為json字符串:
import pandas as pd
data = {
"name": ["John", "Jane", "Mike"],
"age": [30, 25, 35],
"city": ["New York", "London", "Paris"]
}
df = pd.DataFrame(data)
json_data = df.to_json(orient="records")
print(json_data)
  1. 使用Python的yaml庫將yaml文件轉換為json字符串:
import yaml
import json
with open("data.yaml") as file:
yaml_data = yaml.safe_load(file)
json_data = json.dumps(yaml_data)
print(json_data)

這些方法都可以根據數據的格式和需求選擇合適的方式來生成json數據。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女