【发布时间】:2021-03-10 15:16:39
【问题描述】:
我正在将 csv 数据转换为 json 数据,转换数据后,我想添加一个包含每个 json 数据的额外行。请看下图。
#代码
import numpy as np
import pandas as pd
import requests
import json
import csv
import json
def csv_to_json(csvFilePath, jsonFilePath):
jsonArray = []
#read csv file
with open(csvFilePath, encoding='utf-8') as csvf:
#load csv file data using csv library's dictionary reader
csvReader = csv.DictReader(csvf)
#convert each csv row into python dict
for row in csvReader:
#add this python dict to json array
jsonArray.append(row)
#convert python jsonArray to JSON String and write to file
with open(jsonFilePath, 'w', encoding='utf-8') as jsonf:
jsonString = json.dumps(jsonArray, indent=4)
jsonf.write(jsonString)
csvFilePath = r'address.csv'
jsonFilePath = r'address.json'
csv_to_json(csvFilePath, jsonFilePath)
我正在以这种格式从 csv 获取 json。 来自 csv 的 json
[{
"Full Address": "data1",
"p1": "1",
"p2": "6" },
{
"Full Address": "data2",
"p1": "1",
"p2": "6"
}]
但是我想改成这种格式的json。
json
[{
"fields": {
"Full Address": "data1",
"p1": "1",
"p2": "6"
}
},
{
"fields": {
"Full Address": "data2",
"p1": "1",
"p2": "6"
}
}]
【问题讨论】:
-
到目前为止你尝试过什么?请发布您的代码。