简体   繁体   English

Getting only one row in CSV after converting JSON object to CSV file in Python

[英]Getting only one row in CSV after converting JSON object to CSV file in Python

I am totally new to python and i need some help, I'm Getting only one row in CSV file after running this code, the json file is big and has nested arrays Any Suggestions, I am totally new to python and i need some help, I'm Getting only one row in CSV file after running this code, the json file is big and has nested arrays Any Suggestions,

blob_service_client = BlobServiceClient.from_connection_string(constr)
container_client = blob_service_client.get_container_client(container_name)
blob_client = container_client.get_blob_client(filename)
streamdownloader = blob_client.download_blob()
JsonObject = json.loads(streamdownloader.readall())    

def get_leaves(item, key=None):
        if isinstance(item, dict):
            leaves = {}
            for i in item.keys():
                leaves.update(get_leaves(item[i], i))
            return leaves
        elif isinstance(item, list):
            leaves = {}
            for i in item:
                leaves.update(get_leaves(i, key))
            return leaves
        else:
            return {key : item}
    
    fieldnames = set()
    
    for entry in JsonObject:
        fieldnames.update(get_leaves(entry).keys())
    
        with open('C:/Users/Desktop/output.csv', 'w', newline='') as f_output:
            csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
            csv_output.writeheader()
            csv_output.writerows(get_leaves(entry) for entry in JsonObject)

You're opening the file inside loop, it is rewriting the file in each iteration, try this您在循环中打开文件,它在每次迭代中重写文件,试试这个

with open('C:/Users/Desktop/output.csv', 'w', newline='') as f_output:
    csv_output = csv.DictWriter(f_output, fieldnames=sorted(fieldnames))
    csv_output.writeheader()
    for entry in JsonObject:
        fieldnames.update(get_leaves(entry).keys())
        csv_output.writerows(get_leaves(entry) for entry in JsonObject)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM