【问题标题】:Convert Json to CSV using Python使用 Python 将 Json 转换为 CSV
【发布时间】:2018-02-01 17:36:17
【问题描述】:

下面是我从在线气象站提取的 json 结构。我还包括一个 json_to_csv python 脚本,它应该将 json 数据转换为 csv 输出,但只返回一个“Key”错误。我想从“current_observation”中提取数据:仅。

{
  "response": {
  "features": {
  "conditions": 1
  }
    }
  , "current_observation": {
        "display_location": {
        "latitude":"40.466442",
        "longitude":"-85.362709",
        "elevation":"280.4"
        },
        "observation_time_rfc822":"Fri, 26 Jan 2018 09:40:16 -0500",
        "local_time_rfc822":"Sun, 28 Jan 2018 11:22:47 -0500",
        "local_epoch":"1517156567",
        "local_tz_short":"EST",
        "weather":"Clear",
        "temperature_string":"44.6 F (7.0 C)",
    }
}



import csv, json, sys
inputFile = open("pywu.cache.json", 'r') #open json file
outputFile = open("CurrentObs.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
output.writerow(data[0].keys())
for row in data:
    output = csv.writer(outputFile) #create a csv.write 
    output.writerow(data[0].keys())
for row in data:
    output.writerow(row.values()) #values row

检索温度字符串并转换为 .csv 格式的最佳方法是什么?谢谢!

【问题讨论】:

  • 您的代码没有正确缩进;请修复它,以便我们可以运行它。
  • 所以你想要的输出是一个 CSV 文件,其中只有一列的行,每行只显示 temperature_string?
  • 如果可能的话,我想要本地时间、天气和温度字符串。

标签: python export-to-csv


【解决方案1】:
import pandas as pd
df = pd.read_json("pywu.cache.json")
df = df.loc[["local_time_rfc822", "weather", "temperature_string"],"current_observation"].T
df.to_csv("pywu.cache.csv")

也许熊猫可以帮到你。 .read_json() 函数创建了一个不错的数据框,您可以从中轻松选择所需的行和列。它也可以保存为csv。

要将纬度和经度添加到 csv 行,您可以这样做:

df = pd.read_json("pywu.cache.csv")
df = df.loc[["local_time_rfc822", "weather", "temperature_string", "display_location"],"current_observation"].T
df = df.append(pd.Series([df["display_location"]["latitude"], df["display_location"]["longitude"]], index=["latitude", "longitude"]))
df = df.drop("display_location")
df.to_csv("pywu.cache.csv")

要以数值形式打印位置,您可以这样做:

df = pd.to_numeric(df, errors="ignore")
print(df['latitude'], df['longitude'])

【讨论】:

  • 您将如何使用 pandas 解析纬度/经度并以 CSV 格式编写单行输出?
  • 不确定,准确解析是什么意思。例如,可以像这样添加纬度和经度(我会将其添加到答案中)
  • 感谢您修改代码。通过解析,我的意思是从字符串“display_location”中提取纬度和经度。不确定是否可以只显示每个数值?
  • 当然,您可以使用 pd.to_numeric 将生成的 pd.Series() 对象转换为数值。使用 errors="ignore" 您跳过非数字值。然后你可以像字典一样索引对象。 (参见答案中的代码)。并对所有的编辑感到抱歉。
  • NP 与所有编辑 - 它有助于更​​好地理解代码是否放置在 pandas 中。对于您最近添加的内容,我是否直接在 pd.Series 之后和 df.drop 之前添加 pd.to_numeric?
【解决方案2】:

这将找到在 json blob 中指定的所有键(例如“温度字符串”),然后将它们写入 csv 文件。您可以修改此代码以获取多个密钥。

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()

【讨论】:

  • 完美 - 谢谢!
猜你喜欢
  • 2018-01-04
  • 2019-02-23
  • 2021-09-01
  • 2021-12-03
  • 2019-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多