Ошибка TypeError: {'name: busi, group: 1'} не сериализуема в формате JSON при создании json в python с нуля - PullRequest
0 голосов
/ 01 февраля 2019

Как мы можем динамически создать файл json в python, используя данные CSV или данные, представленные в виде списка

data.csv выглядит следующим образом

busi,biz
thank,pump
thank,such
thank,merri

, который показывает ссылки/ ребра между узлами в графе.

Я пытаюсь создать json из узлов и массивов, но получаю ошибку сериализации json.

nodes = []
nodes_dict = {}
counter = 0
edges = open(edges_file)
    for line in edges:
        line = line.replace("\n","")
        source =  line.split(",")[0]
        target = line.split(",")[1]
        if source not in nodes_dict:
            node_arr = {"name:" + source  + "," + "group:1"}
            nodes.append(node_arr)
            nodes_dict[source] = counter
            counter += 1

        if target not in nodes_dict:
            node_arr = {"name:"+ target + "," + "group:1"}
            nodes.append(node_arr)
            nodes_dict[target] = counter
            counter += 1
 json.dumps(nodes,outputfile)

Но я получаю эту ошибку

TypeError: {'name: busi, group: 1'} не поддерживает JSON-сериализацию

Мой желаемый вывод

 "nodes":[
    {"name":"Myriel","group":1},
        {"name":"Napoleon","group":1},
{"name":"Mme.Hucheloup","group":8}],
"links":
            [{"source":1,"target":0,"value":1},{"source":2,"target":0,"value":8},
                {"source":3,"target":0,"value":10},{"source":3,"target":2,"value":6}}
}

1 Ответ

0 голосов
/ 01 февраля 2019

Вы неправильно строите свой диктат.

Попробуйте что-то вроде этого

nodes = []
nodes_dict = {}
counter = 0
edges = open(edges_file)
    for line in edges:
        line = line.replace("\n","")
        source =  line.split(",")[0]
        target = line.split(",")[1]
        if source not in nodes_dict:
            node_arr = dict(
                name=source,
                group=1
            )
            nodes.append(node_arr)
            nodes_dict[source] = counter
            counter += 1

        if target not in nodes_dict:
            node_arr = dict(
                name=target,
                group=1
            )
            nodes.append(node_arr)
            nodes_dict[target] = counter
            counter += 1
 json.dumps(nodes,outputfile)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...