Convert Json to CSV using Python

后端 未结 2 513
难免孤独
难免孤独 2020-12-20 05:27

Below, is the json structure I am pulling from my online weather station. I am also including a json_to_csv python script that is supposed to convert json data to csv outpu

2条回答
  •  忘掉有多难
    2020-12-20 06:01

    This will find all keys (e.g. "temperature_string") specified inside of the json blob and then write them to a csv file. You can modify this code to get multiple keys.

    import csv, json, sys
    
    def find_deep_value(d, key):
    # Find a the value of keys hidden within a dict[dict[...]]
    # Modified from https://stackoverflow.com/questions/9807634/find-all-occurrences-of-a-key-in-nested-python-dictionaries-and-lists
    # @param d dictionary to search through
    # @param key to find
    
        if key in d:
            yield d[key]
        for k in d.keys():
            if isinstance(d[k], dict):
                for j in find_deep_value(d[k], key):
                    yield j
    
    inputFile = open("pywu.cache.json", 'r')  # open json file
    outputFile = open("mypws.csv", 'w')  # load csv file
    data = json.load(inputFile)  # load json content
    inputFile.close()  # close the input file
    output = csv.writer(outputFile)  # create a csv.write
    
    # Gives you a list of temperature_strings from within the json
    temps = list(find_deep_value(data, "temperature_string"))
    output.writerow(temps)
    outputFile.close()
    

提交回复
热议问题