How can I convert JSON to CSV?

前端 未结 26 1664
余生分开走
余生分开走 2020-11-21 22:32

I have a JSON file I want to convert to a CSV file. How can I do this with Python?

I tried:

import json
import c         


        
26条回答
  •  梦谈多话
    2020-11-21 22:52

    Surprisingly, I found that none of the answers posted here so far correctly deal with all possible scenarios (e.g., nested dicts, nested lists, None values, etc).

    This solution should work across all scenarios:

    def flatten_json(json):
        def process_value(keys, value, flattened):
            if isinstance(value, dict):
                for key in value.keys():
                    process_value(keys + [key], value[key], flattened)
            elif isinstance(value, list):
                for idx, v in enumerate(value):
                    process_value(keys + [str(idx)], v, flattened)
            else:
                flattened['__'.join(keys)] = value
    
        flattened = {}
        for key in json.keys():
            process_value([key], json[key], flattened)
        return flattened
    

提交回复
热议问题