【问题标题】:How i can parse the first information in to CSV?我如何将第一个信息解析为 CSV?
【发布时间】:2019-12-09 02:45:03
【问题描述】:

我正在尝试解析 100 多个 json 文件,但我不需要所有信息。 我只需要解析第一组“坐标”,CSV 已经打印了 URL 和 URL 类型,但我无法打印第一组坐标。

这是 Json 文件的一部分

{
  "type":"featureCollection",
  "features" : [
    {
      "type": "feature",
      "geometry": {
        "type": "multilinestring",
        "coordinates":[
          [
            [
              148.9395348,
              -21.3292286
            ],
               [
              148.93963,
              -21.33001
            ],
            [
              148.93969,
              -21.3303
            ]
          ]
        ]
      },
      "properties":{
       "url" :"www.thiswebpageisfake.com",
       "url_type":"fake"
      },
      "information":{
        "timestamp":"10/10/19"
      }
    }]
}

我使用的是 python 2.7,我尝试为坐标创建一个数组,但我有一个类型错误

import os
import csv
import json
import sys

reload(sys)

file_path = 'C:\\Users\\user\\Desktop\\Python\\json'
dirs = os.listdir(file_path)
file_out = 'C:\\Users\\user\\output.csv'
f = csv.writer(open(file_out, "wb+"))
f.writerow(
    ['url','url_type','lat','long'])

for file in dirs:
    json_dict = json.loads(open(os.path.join(file_path, file)).read())
    print file

for key in json_dict['features']:
    for key1 in key:
        description = key['properties']['description']
        if description is None:
            description = 'null'

        array = ()
        array = (key['geometry']['type']['coordinates'])

        f.writerow([file,                                       
                    key['properties']['url'],                    
                    key['properties']['url_type'],     
                    array[1]                                                               
                    ])
print 'completed'

【问题讨论】:

  • 能否在您的问题中粘贴完整的错误信息?
  • Traceback(最近一次调用最后一次):文件“C:/Users/j13sanch/PycharmProjects/jsontocsv_new_zeland/queenslandjson.py”,第 28 行,在 array = (key['geometry'] ['type']['coordinates']) TypeError: 字符串索引必须是整数

标签: python json python-2.7 csv


【解决方案1】:

首先,看起来您的第二个循环应该嵌套在第一个循环中,否则您将不会对除最后一个以外的所有 json 文件执行任何操作,最终只会处理一个文件。

其次,您的数组应定义为array = (key['geometry']['coordinates']),因为'coordinates' 不包含在'type' 中。

【讨论】:

  • 循环是嵌套的,坐标在'type' 内,如果我尝试array = (key['geometry']['coordinates']),就会出现一个关键错误。
  • print(key['geometry']['coordinates']) 添加到您的代码中,看看它是否打印出您想要的内容。 'Coordinates' 肯定不在 'type' 里面。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-05-18
  • 1970-01-01
  • 1970-01-01
  • 2022-12-13
  • 1970-01-01
  • 2011-02-08
相关资源
最近更新 更多