【问题标题】:json converter only takes last key value for last dictionary instead of alljson转换器只取最后一个字典的最后一个键值而不是全部
【发布时间】:2016-10-04 19:20:09
【问题描述】:

好的,所以我有以下字典列表,我正在尝试将其转换为 json 文件:

geojson_list = [

{'name': 'Parallelogram1', 'coordinates':
 [[115.67097179583487, -32.36672530921233], [115.96656222999665,
 -32.36672530921233], [115.90410905434761, -32.49580085924758], [115.60851862018583, -32.49580085924758], [115.67097179583487,
 -32.36672530921233]], 'area': 0.0381534978746},

{'name': 'Parallelogram2', 'coordinates': [[116.00622565359758,
 -32.5791364092627], [116.02283522420637, -32.5791364092627], [116.02126260408991, -32.59706839673082], [116.00465303348112,
 -32.59706839673082], [116.00622565359758, -32.5791364092627]],'area': 0.000297842612008}

]

这是名为 GeojsonConverter.py 的转换器代码:

import json


def convert_to_geojson(my_list):
    """
    This function converts a list of dictionaries into GeoJSON format
    The dictionaries require a "coordinates" key whose value will be a 2D
    list, a "name" key, with all other additional data.
    :param my_list: A list of dictionaries
    :return: a GeoJSON string
    """

    try:
        for d in my_list:
            coord_list = d["coordinates"]
            name = d["name"]
            for coord in coord_list:
                float(coord[0])
                float(coord[1])

    except ValueError:
        print "ValueError: Coordinate cannot be converted to float."
        return "ValueError: Coordinate cannot be converted to float."

    except KeyError:
        print "KeyError: No 'coordinates' or 'name' key found in dictionary"
        return "KeyError: No 'coordinates' or 'name' key found in dictionary"

    except Exception as e:
        raise e

    else:
        feature_list = []
        property_dict = {}

        for d in my_list:
            coord_list = d["coordinates"]
            coord_list.append(d["coordinates"][0])
            name = d["name"]

            for key in d:
                if (key is not "name") and (key is not "coordinates"):
                    property_dict[key] = d[key]

            the_geom = {"type": "MultiPolygon", "coordinates": [[coord_list]]}
            feature = {"type": "Feature", "geometry": the_geom, "name": name, "properties": property_dict}
            feature_list.append(feature)

        feature_collection = {"type": "FeatureCollection", "features": feature_list}

        return json.dumps(feature_collection)

转换器可以很好地转换列表直到区域键。我不断获取所有字典区域的最后一个字典区域中的最后一个值,所以在这种情况下,所有区域 = 0.000297842612008

这是我通过转换器运行列表并将其写入文件后得到的 json 文件:

 { "type": "FeatureCollection", "features": [{"geometry": {"type":
 "MultiPolygon", "coordinates": [[[[115.67097179583487,
 -32.36672530921233], [115.96656222999665, -32.36672530921233], [115.90410905434761, -32.49580085924758], [115.60851862018583,
 -32.49580085924758], [115.67097179583487, -32.36672530921233]]]]}, "type": "Feature", "name": "Parallelogram1", "properties": {"area":
 0.000629970457642}}, 

{"geometry": {"type": "MultiPolygon", "coordinates": [[[[116.00622565359758, -32.5791364092627],
 [116.02283522420637, -32.5791364092627], [116.02126260408991,
 -32.59706839673082], [116.00465303348112, -32.59706839673082], [116.00622565359758, -32.5791364092627]]]]}, "type": "Feature",
 "name": "Parallelogram2", "properties": {"area": 0.000629970457642} }

注意这两个不同的区域在不应该的时候等于相同的结果。

以下代码是我写入文件的方式。

import GeojsonConverter
my_geojson_string = GeojsonConverter2.convert_to_geojson(geojson_list)
name = "test"
try:
    name = name[:-4] #subtract .csv from name to add a character onto the end of the file name. Eg. zzza.csv, not zzz.csva
    with open("./datafiles/" + name + "JSON" + ".geojson", 'w') as jsondata: #Save json data into nameJSON.geojson
        try:
            print ""
            print ("Writing json file: " + name + "JSON" + ".geojson")
            jsondata.write(my_geojson_string)
        except:
            print "Error writing to file. FN: write to file"
            sys.exit()
except:
    print "Error opening file. FN: geojson output"

我哪里出错了?

编辑:

将转换器代码的最后一位更改为此

for d in my_list:
        coord_list = d["coordinates"]
        coord_list.append(d["coordinates"][0])
        name = d["name"]
        area_list = d["area"]

        for key in d:
            if (key is not "name") and (key is not "coordinates") and (key is not "area"):
                property_dict[key] = d[key]
            the_geom = {"type": "MultiPolygon", "coordinates": [[coord_list]]}
            feature = {"type": "Feature", "geometry": the_geom, "name": name, "area": area_list, "properties": property_dict, }
            feature_list.append(feature)

        feature_collection = {"type": "FeatureCollection", "features": feature_list}

【问题讨论】:

  • 有很多问题,我看到的一个是float(coord[0]) 实际上并没有将值更改为浮点数,您需要通过coord[0] = float(coord[0]) 进行更改。
  • 还有这个:coord_list = d["coordinates"] ; coord_list.append(d["coordinates"][0]) 这会将第一项的重复条目添加到列表的末尾,这是需要的吗?
  • 转换后的代码不是我的,实际上它在大约 2 小时前运行良好,从那时起我没有更改任何代码中的任何内容,现在它不起作用
  • 输出中没有重复的条目,当然除了该区域,但这不应该受 coord.list 的影响
  • 啊,我明白了,您在 for 循环之外初始化 property_dict,因此它可用于列表中的两个条目,只需在 for d in my_list: 内初始化它,它将分别用于每个.

标签: python json converter


【解决方案1】:

您遇到了由变量重用引起的问题。

每次运行通过for d in mylist: 都会修改property_dict,然后将其添加到feature_list。下一次循环时,您修改相同的property_dict,它会覆盖以前的数据。将property_dict = {} 移到外循环中可以解决这个问题。

【讨论】:

    猜你喜欢
    • 2022-07-30
    • 2022-12-09
    • 2014-02-23
    • 2018-02-12
    • 1970-01-01
    • 2017-01-07
    • 1970-01-01
    • 1970-01-01
    • 2013-04-14
    相关资源
    最近更新 更多