生成json數據有多種方法,以下是其中幾種常用的方法:
import json
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = json.dumps(data)
print(json_data)
data = {
"name": "John",
"age": 30,
"city": "New York"
}
json_data = str(data).replace("'", '"')
print(json_data)
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)
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數據。