How can I convert JSON to CSV?

前端 未结 26 1636
余生分开走
余生分开走 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:43

    If we consider the below example for converting the json format file to csv formatted file.

    {
     "item_data" : [
          {
            "item": "10023456",
            "class": "100",
            "subclass": "123"
          }
          ]
    }
    

    The below code will convert the json file ( data3.json ) to csv file ( data3.csv ).

    import json
    import csv
    with open("/Users/Desktop/json/data3.json") as file:
        data = json.load(file)
        file.close()
        print(data)
    
    fname = "/Users/Desktop/json/data3.csv"
    
    with open(fname, "w", newline='') as file:
        csv_file = csv.writer(file)
        csv_file.writerow(['dept',
                           'class',
                           'subclass'])
        for item in data["item_data"]:
             csv_file.writerow([item.get('item_data').get('dept'),
                                item.get('item_data').get('class'),
                                item.get('item_data').get('subclass')])
    

    The above mentioned code has been executed in the locally installed pycharm and it has successfully converted the json file to the csv file. Hope this help to convert the files.

    0 讨论(0)
  • 2020-11-21 22:44

    I was having trouble with Dan's proposed solution, but this worked for me:

    import json
    import csv 
    
    f = open('test.json')
    data = json.load(f)
    f.close()
    
    f=csv.writer(open('test.csv','wb+'))
    
    for item in data:
      f.writerow([item['pk'], item['model']] + item['fields'].values())
    

    Where "test.json" contained the following:

    [ 
    {"pk": 22, "model": "auth.permission", "fields": 
      {"codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } }, 
    {"pk": 23, "model": "auth.permission", "fields": 
      {"codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } }, {"pk": 24, "model": "auth.permission", "fields": 
      {"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } }
    ]
    
    0 讨论(0)
  • 2020-11-21 22:46

    This code works for any given json file

    # -*- coding: utf-8 -*-
    """
    Created on Mon Jun 17 20:35:35 2019
    author: Ram
    """
    
    import json
    import csv
    
    with open("file1.json") as file:
        data = json.load(file)
    
    
    
    # create the csv writer object
    pt_data1 = open('pt_data1.csv', 'w')
    csvwriter = csv.writer(pt_data1)
    
    count = 0
    
    for pt in data:
    
          if count == 0:
    
                 header = pt.keys()
    
                 csvwriter.writerow(header)
    
                 count += 1
    
          csvwriter.writerow(pt.values())
    
    pt_data1.close()
    
    0 讨论(0)
  • 2020-11-21 22:46

    This is a modification of @MikeRepass's answer. This version writes the CSV to a file, and works for both Python 2 and Python 3.

    import csv,json
    input_file="data.json"
    output_file="data.csv"
    with open(input_file) as f:
        content=json.load(f)
    try:
        context=open(output_file,'w',newline='') # Python 3
    except TypeError:
        context=open(output_file,'wb') # Python 2
    with context as file:
        writer=csv.writer(file)
        writer.writerow(content[0].keys()) # header row
        for row in content:
            writer.writerow(row.values())
    
    0 讨论(0)
  • 2020-11-21 22:47

    My simple way to solve this:

    Create a new Python file like: json_to_csv.py

    Add this code:

    import csv, json, sys
    #if you are not using utf-8 files, remove the next line
    sys.setdefaultencoding("UTF-8")
    #check if you pass the input file and output file
    if sys.argv[1] is not None and sys.argv[2] is not None:
    
        fileInput = sys.argv[1]
        fileOutput = sys.argv[2]
    
        inputFile = open(fileInput)
        outputFile = open(fileOutput, 'w')
        data = json.load(inputFile)
        inputFile.close()
    
        output = csv.writer(outputFile)
    
        output.writerow(data[0].keys())  # header row
    
        for row in data:
            output.writerow(row.values())
    

    After add this code, save the file and run at the terminal:

    python json_to_csv.py input.txt output.csv

    I hope this help you.

    SEEYA!

    0 讨论(0)
  • 2020-11-21 22:49

    Use json_normalize from pandas:

    • Given the data provided, in a file named test.json.
    • encoding='utf-8' may not be necessary.
    • The following code takes advantage of the pathlib library.
    • .open is a method of pathlib.
    • Works with non-Windows paths too.
    import pandas as pd
    # As of Pandas 1.01, json_normalize as pandas.io.json.json_normalize is deprecated and is now exposed in the top-level namespace.
    # from pandas.io.json import json_normalize
    from pathlib import Path
    import json
    
    # set path to file
    p = Path(r'c:\some_path_to_file\test.json')
    
    # read json
    with p.open('r', encoding='utf-8') as f:
        data = json.loads(f.read())
    
    # create dataframe
    df = pd.json_normalize(data)
    
    # dataframe view
     pk            model  fields.codename           fields.name  fields.content_type
     22  auth.permission     add_logentry     Can add log entry                    8
     23  auth.permission  change_logentry  Can change log entry                    8
     24  auth.permission  delete_logentry  Can delete log entry                    8
      4  auth.permission        add_group         Can add group                    2
     10  auth.permission      add_message       Can add message                    4
    
    # save to csv
    df.to_csv('test.csv', index=False, encoding='utf-8')
    

    CSV Output:

    pk,model,fields.codename,fields.name,fields.content_type
    22,auth.permission,add_logentry,Can add log entry,8
    23,auth.permission,change_logentry,Can change log entry,8
    24,auth.permission,delete_logentry,Can delete log entry,8
    4,auth.permission,add_group,Can add group,2
    10,auth.permission,add_message,Can add message,4
    

    Other Resources for more heavily nested JSON objects:

    • SO Answers:
      • Flatten a JSON array with python
      • How to flatten nested JSON recursively, with flatten_json?
      • How to json_normalize a column with NaNs
    0 讨论(0)
提交回复
热议问题