JSON不可序列化 - json.dump无法正确识别列表

时间:2016-05-05 17:52:37

标签: json list python-2.7 serializable

我正在尝试从给定的dicts列表中创建一个json转储。 值的格式如下

  

[{'id1':1,'id2':2,'距离':23},{'id1':1,'id2':2,'距离':23}]

当我运行代码(粘贴在下面)时,它给了我一个JSON不可序列化的TypeError。问题是即使变量'distance_list'被初始化为列表(使用distance_list = list()),函数 isinstanceof(distance_list,list)返回false显示该python不会将该变量识别为列表对象。

但是print(distance_list)显示'list'。 我很迷惑。我的问题是,如何打印显示'列表'类型和isinstanceof()不将其标识为'列表'?因为python没有将它标识为列表,所以json.dump失败。

调用函数()

def create_habitat_pairs_and_save(pdata_unsorted, field_radius, outputfile):

ulog.logit(2, "Entering function create_habitat_pairs_and_save... ")
distance_list = list()
rowCounter = 0
irowcount = 0
loop_counter = 0
sort_colname_coordinates = ['mapX', 'mapY']  # sort columns for pandas dataframe

rowcount = len(pdata_unsorted.index)
pdata = sortdata(pdata_unsorted, sort_colname_coordinates)  # sort input file contents by X and Y coordinates    

for index_i, row_i in pdata.iterrows():
    loop_counter += 1
    utilities.show_progress(loop_counter, rowcount)  #show progress on screen
    irowcount+=1
    pointer = irowcount
    x1 = int(row_i['mapX'])
    y1 = int(row_i['mapY'])
    rowCounter = 0
    yrange_trigger = False

    for index_j, row_j in pdata[pointer: rowcount].iterrows():
        x2 = int(row_j['mapX'])
        y2 = int(row_j['mapY'])
        rowCounter += 1
        if x2 <= x1 + field_radius:
            if y2 < y1 - field_radius:
                continue
            else:
                if y2 >= y1 - field_radius and y2 <= y1 + field_radius:
                    yrange_trigger = True
                    distance = compute_distance(x1, y1, x2, y2)
                    if distance <= field_radius and distance != 0:
                        entry = {'id1':row_i['id'], 'id2': row_j['id'], 'distance': distance}
                        distance_list.append(entry)
                else:
                    break
        else:
            break
writefile(distance_list, outputfile)  # write the habitat pairs into json file for future use

要写入json的文件(从上面的函数调用)

def writefile(distance_list, filename):
ulog.logit(2, "writefile... ")
with open(filename, mode = 'w+') as f:
        json.dump(distance_list, f)
f.close()

0 个答案:

没有答案