2016-09-09 4 views
0

중첩 된 JSON을 Python을 사용하여 Excel 파일 형식으로 변환하려고합니다. 나는 거의 요구 사항에 따라 일을했지만, 나는 아래와 같이 엑셀 형식을 얻고 싶다.Python을 사용하여 중첩 JSON을 Excel로 변환

JSON

[ 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Cooktops/zgbs/appliances/3741261", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Cooktops" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Dishwashers/zgbs/appliances/3741271", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Dishwashers/zgbs/appliances/3741281", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Built-In Dishwashers" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Portable-Countertop-Dishwashers/zgbs/appliances/3741301", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Portable & Countertop Dishwashers" 
 
     } 
 
    ], 
 
    "title": "Dishwashers" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Freezers/zgbs/appliances/3741331", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Chest-Freezers/zgbs/appliances/3741341", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Chest Freezers" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Upright-Freezers/zgbs/appliances/3741351", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Upright Freezers" 
 
     } 
 
    ], 
 
    "title": "Freezers" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Ice-Makers/zgbs/appliances/2399939011", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Ice Makers" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Range-Hoods/zgbs/appliances/3741441", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Range Hoods" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Ranges/zgbs/appliances/3741411", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Drop-Ranges/zgbs/appliances/3741421", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Drop-In Ranges" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Ranges/zgbs/appliances/3741431", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Freestanding Ranges" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Slide-Ranges/zgbs/appliances/2399946011", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Slide-In Ranges" 
 
     } 
 
    ], 
 
    "title": "Ranges" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Refrigerators/zgbs/appliances/3741361", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Refrigerators" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Wall-Ovens/zgbs/appliances/3741481", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Microwave-Wall-Ovens/zgbs/appliances/3741491", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Combination Microwave & Wall Ovens" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Double-Wall-Ovens/zgbs/appliances/3741501", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Double Wall Ovens" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Single-Wall-Ovens/zgbs/appliances/3741511", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Single Wall Ovens" 
 
     } 
 
    ], 
 
    "title": "Wall Ovens" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Warming-Drawers/zgbs/appliances/2399955011", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Warming Drawers" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Washers-Dryers/zgbs/appliances/2383576011", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Dryers/zgbs/appliances/13397481", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Dryers" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Clothes-Washing-Machines/zgbs/appliances/13397491", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Washers" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Combination-Washers-Dryers/zgbs/appliances/13755271", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "All-in-One Combination Washers & Dryers" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Stacked-Washer-Dryer-Units/zgbs/appliances/2399957011", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Stacked Washer & Dryer Units" 
 
     } 
 
    ], 
 
    "title": "Washers & Dryers" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellars/zgbs/appliances/3741521", 
 
    "subCategory": [ 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Built-Wine-Cellars/zgbs/appliances/3741551", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Built-In Wine Cellars" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Freestanding-Wine-Cellars/zgbs/appliances/3741541", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Freestanding Wine Cellars" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Furniture-Style-Wine-Cellars/zgbs/appliances/3741561", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Furniture-Style Wine Cellars" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Small-Wine-Cellars/zgbs/appliances/3741531", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Small Wine Cellars" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Cellar-Cooling-Systems/zgbs/appliances/3741581", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Wine Cellar Cooling Systems" 
 
     }, 
 
     { 
 
     "url": "https://www.amazon.com/Best-Sellers-Appliances-Wine-Rooms/zgbs/appliances/3741571", 
 
     "subCategory": [ 
 
      
 
     ], 
 
     "title": "Wine Rooms" 
 
     } 
 
    ], 
 
    "title": "Wine Cellars" 
 
    }, 
 
    { 
 
    "url": "https://www.amazon.com/Best-Sellers-Appliances-Home-Appliance-Warranties/zgbs/appliances/2242350011", 
 
    "subCategory": [ 
 
     
 
    ], 
 
    "title": "Appliance Warranties" 
 
    } 
 
]

이 같은 모든 하위 범주를 탐색 해요 :

row = 1 

def TraverseJSONTree(jsonObject, count=0): 
    title = jsonObject.get('title') 
    url = jsonObject.get('url') 

    print 'Title: ' + title + ' , Position: ' + str(count) 

    worksheet.write_string(row, count, title) 
    worksheet.write_string(row, 6, url) 
    global row 
    row+=1 

    subCategories = jsonObject.get('subCategory',[]) 

    for category in subCategories: 
     TraverseJSONTree(category, count+1) 


for jsonObject in json.loads(jsonArray): 
    TraverseJSONTree(jsonObject) 

enter image description here

예상 결과

수정

enter image description here

+0

사용할 수있는 파이썬 코드 (http://stackoverflow.com/questions/29196668/mapping-a-json-file-to-excel-with-을 사용할 수 있습니다 파이썬) – bhansa

+0

어떻게 말해 줄 수 있습니까? 나는 요구 사항에 따라 거의 할 수 있었다. 저는 파이썬에서 초보자입니다 –

답변

0

: CSV 모듈을 사용하는 것이 작업을 수행하는 가장 간단한 방법은, 우리는 변수의 전체 JSON이 있다고 당신이 원하는 것

import csv 
import cPickle as pickle 

fieldnames = ['Category1', 'Category1.1', 'url'] 
csvfile = open("category.csv", 'wb') 
csvfilewriter = csv.DictWriter(csvfile, fieldnames=fieldnames,dialect='excel', delimiter=',') 
csvfilewriter.writeheader() 

for b in a:  
    data = [] 
    data.append(b['title']) 
    data.append("") 
    data.append(b['url']) 
    csvfilewriter.writerow(dict(zip(fieldnames,data))) 
    data = [] 
    for i in xrange(len(b['subCategory'])): 
     data.append(b['title']) 
     data.append(b['subCategory'][i]['title']) 
     data.append(b['subCategory'][i]['url']) 
     csvfilewriter.writerow(dict(zip(fieldnames,data))) 

같은 위치에있는 CSV. 이것은 두 개의 하위 카테고리에만 적용됩니다 (내가 제공 한 데이터를 확인하고 두 가지 카테고리 (예 : 1과 1.1)이 있다고 말했기 때문에).하지만 반복 할 필요가있을 경우를 대비하여 (가장 효율적인 방법은 아닙니다.) 짧은 시간에 어떤 생각하지 못했습니다

또한 PD로 사전 수입 팬더를 변환 팬더 모듈을 사용할 수 있습니다

pd.DataFrame.from_dict (dcitionaty_element)

그리고 모두에 그것을 할 그 json에있는 사전들은 그들을 병합하고 csv 파일에 저장합니다. 카테고리는 다음 Excel에서 0 번째 COL에 원래 제목을 오른쪽으로있다가이 같은 reamin 경우는 수표를 필요로

+1

작업 솔루션을 제공하십시오 –

+0

하위 범주의 하위 범주가있는 경우이 방법을 사용할 수 있습니까? –

+0

하위 카테고리 중 최대 개수가 무엇인지 아는 경우 for 루프를 다시 사용하면됩니다. –

1
row = 1 

def TraverseJSONTree(jsonObject, main_title=None, count=0): 
    if main_title is None: 
     main_title = title = jsonObject.get('title') 
    else: 
     title = jsonObject.get('title') 
    url = jsonObject.get('url') 

    print 'Title: ' + title + ' , Position: ' + str(count) 

    if main_title is not None: 
     worksheet.write_string(row, 0, title) 
    worksheet.write_string(row, count, title) 
    worksheet.write_string(row, 6, url) 
    global row 
    row+=1 

    subCategories = jsonObject.get('subCategory',[]) 

    for category in subCategories: 
     TraverseJSONTree(category, main_title, count+1) 

for jsonObject in json.loads(jsonArray): 
    TraverseJSONTree(jsonObject) 

은 당신의 예상 출력을 반환합니다.

+0

위에서 언급 한대로 원하는 출력을 제공하지 않습니다. 귀하의 스크립트를 확인한 결과 다음과 같습니다. https://docs.google.com/spreadsheets/d/1BBlXNiCqn-Z19cCsK_kzpS4fpy4Rknek2ubyvEj4c5E/edit?usp=sharing –

+0

https : // docs와 같이해야합니다. google.com/spreadsheets/d/1TT5alzmW9tMSR1sOFoi1YgYz_IwnTGUvhh1esHhk8QM/edit?usp=sharing 하위 카테고리의 하위 카테고리가 더 있으면 작동해야합니다. –

+1

Ahh 어리석은 실수는 다음 줄에서 main_title로 제목을 업데이트하는 것입니다. main_title이 아닌 경우 : worksheet.write_string (row, 0, main_title) –

0

당신은 [팬더]와 쉬운 것입니다 here

관련 문제