【问题标题】:How to convert json to csv in python?如何在python中将json转换为csv?
【发布时间】:2020-12-19 11:27:06
【问题描述】:

我有一个嵌套的 json 文件可以将其转换为 csv 。下面是 json 格式,

[{'year': '2020' }, 
('data', [{'location': {'coordinates': {'lat': 22.0, 'lon': -33.0}}, 
'times': {'date': '2020-08-30', 'time': '12:00'}, 
'values': {'surface': 45, 'wave': 6.8, 'temp': 283, 'height': 1.8}},
{'location': {'coordinates': {'lat': 22, 'lon': -33}},
'times': {'date': '2020-08-30', 'time': '13:00'}, 
'values': {'surface': 42, 'wave': 6.7, 'temp': 283.1, 'height': 2.88}})]

这些json格式要转换成csv:

需要的输出如下:

lat  lon  date       time   surface  wave  temp  height
22   -33  2020-08-30 12:00   45      6.8   283    1.8
22   -33  2020-08-30 13.00   42      6.7   283.1  2.88

【问题讨论】:

  • 你试过什么?你被困在哪里了?
  • 您发布的json无效

标签: python json python-3.x pandas csv


【解决方案1】:

如果您设法将嵌套的 JSON 更改为以下内容:

{
        "year": 2020,
        "data": {
            "location": {
                "coordinates": {
                    "lat": 22.0,
                    "lon": -33.0
                }
            },
            "times": { 
                "date": "2020-08-30",
                "time": "12:00"
             },
            "values": { 
                "surface": "2020-08-30",
                "wave": "12:00",
                "temp": 283,
                "height": 1.8
             }
        }
    },
    ...

您可以使用此代码转换为csv

import csv
import json

x = """[
    {
        "year": 2020,
        "data": {
            "location": {
                "coordinates": {
                    "lat": 22.0,
                    "lon": -33.0
                }
            },
            "times": { 
                "date": "2020-08-30",
                "time": "12:00"
             },
            "values": { 
                "surface": "2020-08-30",
                "wave": "12:00",
                "temp": 283,
                "height": 1.8
             }
        }
    },
   
]"""

x = json.loads(x)

f = csv.writer(open("Example.csv", "wb+"))

# Write CSV Header, If you dont need that, remove this line
f.writerow(["year", "data", "location", "times", "values"])

for x in x:
    f.writerow([x["year"],
                x["data"],
                x["location"]["coordinates"]["lat"],
                x["location"]["coordinates"]["lon"],
                x["times"]["date"],
                x["times"]["time"],
                x["values"]["surface"],
                x["values"]["wave"],
                x["values"]["temp"],
                x["values"]["height"]])

【讨论】:

  • for x in x 这是什么?
  • 写更长的for循环的另一种方式
猜你喜欢
  • 2016-11-05
  • 2019-05-28
  • 2020-05-31
  • 1970-01-01
  • 2015-08-07
  • 1970-01-01
  • 2019-04-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多