json转换器只取最后一个字典的最后一个键值而不是全部

时间:2016-06-04 23:55:49

标签: python json converter

好的,我有以下dictionarys列表,我试图转换为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}

1 个答案:

答案 0 :(得分:1)

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

每次浏览for d in mylist:都会修改property_dict,然后会将其添加到feature_list。下一次循环,您修改相同的property_dict ,它会覆盖以前的数据。将property_dict = {}移动到外部循环将解决此问题。