Did I find the right examples for you? yes no

All Samples(2)  |  Call(1)  |  Derive(0)  |  Import(1)
Convert a JSON document into CSV format.

The top-level element of the input must be a list or a dictionary. If it is a dictionary, a key must be provided which is an item of the dictionary which contains a list.

        def json2csv(f, key=None, **kwargs):
    """
    Convert a JSON document into CSV format.

    The top-level element of the input must be a list or a dictionary. If it is a dictionary, a key must be provided which is an item of the dictionary which contains a list.
    """
    document = f.read()
    js = json.loads(document)

    if isinstance(js, dict):
        if not key:
            raise TypeError('When converting a JSON document with a top-level dictionary element, a key must be specified.')
        
        js = js[key]

    if not isinstance(js, list):
        raise TypeError('Only JSON documents with a top-level list element are able to be converted (or a top-level dictionary if specifying a key).')

    field_set = set()
    flat = []

    for obj in js:
        flat.append(parse_object(obj)) 

    for obj in flat:
        field_set.update(obj.keys())

    fields = sorted(list(field_set))

    o = StringIO()
    writer = CSVKitWriter(o)

    writer.writerow(fields)

    for i in flat:
        row = []

        for field in fields:
            if field in i:
                row.append(i[field])
            else:
                row.append(None)

        writer.writerow(row)

    output = o.getvalue()
    o.close()

    return output
        


src/c/s/csvkit-0.7.3/csvkit/convert/__init__.py   csvkit(Download)
from fixed import fixed2csv
from geojs import geojson2csv
from js import json2csv
from xls import xls2csv
from xlsx import xlsx2csv
        return xlsx2csv(f, **kwargs)
    elif format == 'json':
        return json2csv(f, key, **kwargs)
    elif format == 'geojson':
        return geojson2csv(f, **kwargs)