Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python json转换器只接受最后一个字典的最后一个键值,而不是全部_Python_Json_Converter - Fatal编程技术网

Python json转换器只接受最后一个字典的最后一个键值,而不是全部

Python json转换器只接受最后一个字典的最后一个键值,而不是全部,python,json,converter,Python,Json,Converter,好的,下面是我试图转换为json文件的字典列表: geojson_list = [ {'name': 'Parallelogram1', 'coordinates': [[115.67097179583487, -32.36672530921233], [115.96656222999665, -32.36672530921233], [115.90410905434761, -32.49580085924758], [115.60851862018583, -32.49580085924

好的,下面是我试图转换为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}

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


每次运行mylist中d的
都会修改
属性dict
,然后将其添加到
功能列表中。下次通过循环时,您将修改相同的
属性_dict
,该属性将覆盖以前的数据。将
property_dict={}
移动到外部循环将解决这个问题。

有许多问题,我看到的一个问题是
float(coord[0])
实际上并没有将值更改为float,您需要执行
coord[0]=float(coord[0])
来更改它;coord_list.append(d[“coordinates”][0])
这将在列表的末尾添加第一项的重复条目,是否需要?转换后的代码不是我的,实际上它在大约2小时前工作正常,从那时起,我在两个代码中都没有更改任何内容,现在它不工作输出上没有重复条目,当然,除了这个区域之外,但是这不应该受到coord.listahh的影响,我知道,您在for循环之外初始化
property\u dict
,这样它就可以对列表中的两个条目重复使用,只需在
for d in my\u list:
中对其进行初始化,并且它将分别用于每个条目。