在python中创建列表的嵌套列表...(真的是csv - > json转换)

时间:2017-03-11 05:39:43

标签: python json csv

我一直在努力解决这个应该很容易的问题 - 我只是对Python很新,在这种情况下是必需的。

我正在准备.csv文件并试图创建一个嵌套结构,以便json.dumps给我一个非常好的嵌套.json文件。

结果json实际上是六级深,但我想如果我可以得到底部两个工作,其余的将是相同的。输入工作正常,因为我最终得到了作业[' fieldname ']来构建结构。问题是让结果嵌套。

最终我想:

"PAYLOAD": {
  "TEST": [
   {
     "JOB_ONE": {
       "details": {
         "customerInformation": {
           "lastName": "Chun",
           "projectName": "N Pacific Recovery",
           "firstName": "Wally",
           "secondaryPhoneNumber": ""
            },
         "description": "N Pacific Garbage Sweep",
         "productType": "Service Generation",
         "address": {
           "city": "Bristol",
           "zipCodePlusSix": "",
           "stateName": "",
           "zipCode": "53104",
           "line1": "12709 789441th Ave",
           "county": "",
           "stateCode": "WI",
           "usage": "NA",
           "zipCodePlusFour": "",
           "territory": "",
          }
       }
     }
   },
 {
   "JOB_TWO": {
     "details": {

   .... similar to JOB_ONE ....

       }
     }
   }
   }],
   "environment": "N. Pacific",
   "requestorName": "Waldo P Rossem",
   "requestorEmail": "waldo@ no where.com",

但是,使用下面的代码,它只处理“详细信息部分”,我最终得到一堆所有地址,然后是所有客户信息。因此,循环处理所有csv记录并附加地址,然后循环csv记录并附加信息。

for job in csv.DictReader(csv_file):
  if not job['Cancelled']: 

# actually have no idea how to get these two to work    
    details['description']: job['DESCRIBE']     
    details['projectType']: job['ProjectType']


# the following cycle through the customerInformation and then
# appends the addresses.  So I end up with a large block of customer 
# records and then a second block of their addresses

    details['customerInformation'].append({
            'lastName': "job[Lastname]",
            'firstName': job['FirstName'],
            'projectName':"N Pacific Prototype",
        })

   details['address'].append({
            'city': job['City'],
            'zipCode': job['Zip'],
            'line1': job['Address'],
            'stateCode': job['State'],
            'market': job['Market']
        })

我想要了解的是如何修复此循环并使描述和项目类型出现在正确的位置并设置数据结构,以便底部标志也适用于最终的json转储。

这很大程度上是由于我缺乏使用Python的经验,但不幸的是,这是一个要求 - 否则,我可以在几小时前使用 gawk 完成它!

请求的CSV如下:

当然......花了我一段时间来假装它,因为上面是一个简短的片段。

JobNumber,FirstName,Lastname,secondaryPhoneNumber,Market,Address,City,State,Zip,requestorName,requestorEmail,environment
22056,Wally,Fruitvale,,N. Pacific,81 Stone Church Rd,Little Compton,RI,17007,Waldo P Rossem,waldo@ no where.com,N. Pacific
22057,William,Stevens,,Southwest,355 Vt Route 8a,Jacksonville,VT,18928,Waldo P Rossem,waldo@ no where.com,N. Pacific
22058,Wallace,Chen,,Northeast,1385 Jepson Rd,Stamford,VT,19403,Waldo P Rossem,waldo@ no where.com,N. 

3 个答案:

答案 0 :(得分:2)

您可以将details字词创建为文字与创建和key作业:

data = []
for job in csv.DictReader(csv_file):
    if job['Cancelled']:
        continue
    details = {
        'description': job['DESCRIBE'],
        'projectType': job['ProjectType'],
        'customerInformation' : {
            'lastName': job['Lastname'],
            'firstName': job['FirstName'],
            ...
        },
        ...
    }
    data.append(details)
json_str = json.dumps(data)

答案 1 :(得分:1)

我认为你的谜题需要的只是了解一些关于词典的基本知识:

初始分配:

my_dict = {
   "key1": "value1",
   "key2": "value2",
   ...
}

将键/值对写入已初始化的字典:

my_dict["key2"] = "new value"

读:

my_dict["key2"]
prints> "new value"

循环键:

for key in my_dict:
   print(key)

prints> "key1"
prints> "key2"

循环键和值:

for key, value in my_dict.items():
   ...

仅循环值:

for value in my_dict.values():
   ...

如果你想要的只是一个JSON兼容的词典,那么除了这个之外你不需要太多的东西,没有我进入默认值,元组键等等 - 只要知道一旦你想到它就值得读一读基本的词组,列表,元组和集合。

编辑:还有一件事:即使是新的,我认为值得尝试Jupyter notebook来探索你在Python中的想法。我发现尝试并立即恢复结果要快得多,因为你不必在编辑器和控制台之间切换。

答案 2 :(得分:0)

你离我不远。 您首先需要将details初始化为dict

details = {}

然后添加您想要的元素:

details['description'] = job['DESCRIBE']     
details['projectType'] = job['ProjectType']

然后是嵌套的:

details['customerInformation'] = {
        'lastName': job['Lastname'],
        'firstName': job['FirstName'],
        'projectName':"N Pacific Prototype",
    }

有关如何使用dicthttps://docs.python.org/3/library/stdtypes.html?highlight=dict#dict的详细信息。

然后,您可以使用JSON获取JSON.dumps(details)(此处提供文档:https://docs.python.org/3/library/json.html?highlight=json#json.dumps)。

或者您可以先收集列表中的所有详细信息,然后将列表转换为JSON字符串:

all_details = []
for job in ...:
    (build details dict)
    all_details.append(details)

output = JSON.dumps(all_details)