Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/321.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/arduino/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将带有嵌套标题的CSV转换为JSON_Python_Json_Csv_Parsing - Fatal编程技术网

Python 将带有嵌套标题的CSV转换为JSON

Python 将带有嵌套标题的CSV转换为JSON,python,json,csv,parsing,Python,Json,Csv,Parsing,到目前为止,我有以下代码(在教程的帮助下): 我想要的输出是: { "userID": "string", "username": "string", "age": "string", "location": { "streetName": "string", "stre

到目前为止,我有以下代码(在教程的帮助下):

我想要的输出是:

{
  "userID": "string", 
  "username": "string", 
  "age": "string",
  "location": {
    "streetName": "string", 
    "streetNo": "string", 
    "city": "string"
  }
}
{
    "userID": "string", 
    "username": "string", 
    "age": "string",
    "location/streetName": "string", 
    "location/streetNo": "string", 
    "location/city": "string", 
}
我不知道如何表示“位置”

我的实际结果是:

{
  "userID": "string", 
  "username": "string", 
  "age": "string",
  "location": {
    "streetName": "string", 
    "streetNo": "string", 
    "city": "string"
  }
}
{
    "userID": "string", 
    "username": "string", 
    "age": "string",
    "location/streetName": "string", 
    "location/streetNo": "string", 
    "location/city": "string", 
}

如何将streetName、streetNo和city分离并将它们放入“位置”?

我会添加一些自定义逻辑来实现这一点,请注意,这仅适用于第一级,如果您需要更多,您应该创建一个恢复功能:

# Write data to a JSON file...
with open(jsonFilePath, "w") as jsonFile:
    for i, v in data.items():
        if '/' in i:
            parts = i.split('/', 1)
            data[parts[0]] = {parts[1]: v}
            data.pop(i)

    jsonFile.write(json.dumps(data, indent=4))

您可以使用以下内容:

#https://www.geeksforgeeks.org/convert-csv-to-json-using-python/
导入csv
导入json
#函数将CSV转换为JSON
#将文件路径作为参数
def make_json(csvFilePath,jsonFilePath):
#创建字典
数据={}
#打开名为DictReader的csv读取器
将open(csvFilePath,encoding='utf-8')作为csvf:
csvReader=csv.DictReader(csvf)
#将每行转换为字典
#并将其添加到数据中
对于csvReader中的行:
#假设一个名为“No”的列
#成为主键
键=行['No']
数据[键]=行
#打开json编写器,并使用json.dumps()命令
#用于转储数据的函数
将open(jsonFilePath,'w',encoding='utf-8')作为jsonf:
write(json.dumps(数据,缩进=4))
#驱动程序代码
#根据需要确定两个文件路径
#计算机系统
csvFilePath=r'Names.csv'
jsonFilePath=r'Names.json'
#调用make_json函数
生成json(csvFilePath、jsonFilePath)

有关更多信息,请查看下面的一个简单脚本,该脚本可以执行您想要的操作。结果将是一个以“userID”作为键的json对象。请注意,为了测试更深层次的嵌套,我使用了一个标题稍有不同的csv文件——但它与您的原始示例同样适用

import csv, json

infile = 'convertcsv.csv'
outfile = 'newResult.json'

data = {}

def process(header, value, record):
    key, other = header.partition('/')[::2]
    if other:
        process(other, value, record.setdefault(key, {}))
    else:
        record[key] = value

with open(infile) as stream:
    reader = csv.DictReader(stream)
    for row in reader:
        data[row['userID']] = record = {}
        for header, value in row.items():
            process(header, value, record)

with open(outfile, "w") as stream:
    json.dump(data, stream, indent=4)
输入:

userID、用户名、年龄、位置/街道/姓名、位置/街道/号码、位置/城市
0,AAA,20,这条街,5,这座城市
1号BBB 42号那条街5号那座城市
CCC 2号,34号,其他街道,5号,其他城市
输出:

{
"0": {
“用户ID”:“0”,
“用户名”:“AAA”,
“年龄”:“20岁”,
“地点”:{
“街道”:{
“名称”:“这条街”,
“编号”:“5”
},
“城市”:“这座城市”
}
},
"1": {
“用户ID”:“1”,
“用户名”:“BBB”,
“年龄”:“42”,
“地点”:{
“街道”:{
“名称”:“那条街”,
“编号”:“5”
},
“城市”:“那个城市”
}
},
"2": {
“用户ID”:“2”,
“用户名”:“CCC”,
“年龄”:“34岁”,
“地点”:{
“街道”:{
“名称”:“其他街道”,
“编号”:“5”
},
“城市”:“其他城市”
}
}
}

嘿,谢谢!你能给我解释一下我怎样才能为它创建一个补偿函数吗?我想弄清楚,但不知道更多。。。现在它只有“地点/城市”