Python json问题-驼峰式和双引号

时间:2020-09-26 12:26:29

标签: python json csv

我必须读取一个csv文件并从中创建一个JSON列表。目前,我首先阅读每一行,添加到列表中,并使用JSON转储来创建JSON输出。我面临两个问题

  1. JSON转储将单引号添加到属性中,这不是我想要的。我希望每个键值对都用自己的双引号引起来。

  2. 它使用的是CSV文件头,而不是驼峰式的键,但是我需要驼峰式的键

这是我的程序产生的

{
"Reqlist":[
    {
        'FieldName1' : 'val1'       
    },
    {
        'Fieldname2' : 'val2'
    }
    ],
    
    'metaData' : 'metaVal'
}



This is the output I expect 

{
"Reqlist":[
    {
        "fieldName1" : "val1"       
    },
    {
        "fieldName2" : "val2"
    }
    ],
    
    "metaData" : "metaVal"
}

示例代码:

reader = csv.DictReader(open(file_data), restkey='INVALID', restval='INVALID')
        headers = reader.fieldnames
        error_count = 0
        success_count =0
        dict=[]
        header_count = set(headers)
        json_error_data = json.dumps({})
        csv_list =[]
        error_list={}
        myDict =[] 
        print(headers)
        if(len(header_count)!=constants.EXPECTED_HEADER_COUNT or (set(headers)!=set(constants.FIELD_NAMES))):
            print('error for record')
        else:
            for row in reader:
                if('INVALID' in row.values()):
                    error_count +=1
                else:
                    success_count +=1
                    csv_list.append(row)
    except Exception as e:
        logging.error('error')

    if(error_count>0 and success_count == 0 ):
        print('save the errors')
    elif(success_count>0):
        jsonlist = json.dumps({'Reqlist': csv_list })
        new = json.loads(jsonlist)
        a_dict = {'metaData': 'metaVal'}
        new.update(a_dict)

1 个答案:

答案 0 :(得分:0)

def convert_to_camel(dict1):
    new_dict = {}
    for key, value in dict1.items():
        key = key[0].lower() + key[1:]

        value = value if type(value) is not dict else convert_to_camel(value)
        new_dict[key] = value
    return new_dict

csv_list = [convert_to_camel(i) for i in csv_list]

这应该适用于骆驼案

对于单引号,我为python写了一个类似于json的库。这不是完美的,但是here是完美的。