【问题标题】:Add extra object which contains each JSON data in python在 python 中添加包含每个 JSON 数据的额外对象
【发布时间】: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"
 }
 }]

Picture

【问题讨论】:

  • 到目前为止你尝试过什么?请发布您的代码。

标签: python json csv


【解决方案1】:

您可以使用列表推导将从DictReader 读取的每个dict 行巧妙地包装在"fields" 键中。

另外,去掉所有多余的“绒毛”,你的功能就变得简单了

def csv_to_json(csvFilePath, jsonFilePath):
    with open(csvFilePath, encoding="utf-8") as csvf:
        arr = [{"fields": row} for row in csv.DictReader(csvf)]
    with open(jsonFilePath, "w", encoding="utf-8") as jsonf:
        json.dump(arr, jsonf, indent=4)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-09
    • 2015-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-09-24
    相关资源
    最近更新 更多