多级JSON/嵌套字典到JSON

2024-09-22 18:27:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要采取两个tsv文件,并结合起来,使他们成为一个多层次的json,我将使用它来制作一个图形。你知道吗

然而,我的边列表是一个限制因素,这意味着我的节点csv中有更多的节点,而不是我想要的图形。我只关心如何在边缘文件中表示节点。你知道吗

首先,我需要在一个较小的'边缘名单'的tsv阅读。你知道吗

//Example
    source  target  edgeWeight
    NODEA   NODE1   27
    NODEB   NODE2   44
    NODEC   NODE3   28
    NODED   NODE4   46
    NODEE   NODE5   37
    NODEF   NODE6   46
    NODEG   NODE7   58

然后我需要检查第二个csv,看看这些节点是否存在。如果是,我想把它们加到元素.节点你知道吗

#check to see
//Example
NodeList    edgeWeight
NODEA   7
NODEB   3
NODEC   1
NODEG   9
NODEM   12 // this node wouldn't be created since it isn't present in edges
NODE3   4
NODE4   8
NODE7   1
NODE2   4
NODED   3
NODE1   4

我需要最后一个json文件如下所示:

  "elements" : {
    "nodes" : [ {
      "data" : {
        "id" : "NODEB",

       "weight" : 1

      },
    }, {
      "data" : {
        "id" : "NODE3,
       "weight" : 20
        },
    }, {
      "data" : {
        "id" : "NODED",
       "weight" : 60
      },
    }, {
      "data" : {
        "id" : "NODE1",
       "weight" : 80
      },

    }, {
      "data" : {
        "id" : "NODEA",
       "weight" : 100
      },

    } ], 
    "edges" : [ {
      "data" : {
        "id" : "1",
        "source" : "NODEA",
        "target" : "NODED", 
        "weight": 40
      },

    }, {
      "data" : {
        "id" : "2",
        "source" : "NODEG",
        "target" : "NODE2",
        "weight": 4
      },

    }, {
      "data" : {
        "id" : "3",
        "source" : "NODEA",
        "target" : "NODEB",
        "weight": 1
},

    },  ]
  }
}

它适用于JavaScript应用程序,不过python也可以。你知道吗

***************************更新***************************** 这里有一些澄清和我迄今为止所做的尝试。 元素 / \ 节点边缘 / \ 数据 / \ / \ \ ID权重源目标权重

到目前为止,我已经能够创建一个csv->;pythondict->;json(下面的代码),但只针对节点和边,我不知道如何组合它们。你知道吗

import csv
import json
import sys

Edgecsvfile = open('SmallEdge.csv', 'r')
#creating new to write 
Ejsonfile = open('E2.json', 'wb')

#how to label
Efieldnames = ("source","target","count")
#creating reader 
Ereader = csv.DictReader( Edgecsvfile, Efieldnames)
for row in Ereader:
    json.dump(row, Ejsonfile, indent = 3)
    Ejsonfile.write('\n')


Nodecsvfile = open('SmallNode.csv', 'r')
Njsonfile = open('N2.json', 'wb')

Nfieldnames = ("source","total_mutations")
Nreader = csv.DictReader( Nodecsvfile, Nfieldnames)
for row in Nreader:
    json.dump(row, Njsonfile, indent = 2)
    Njsonfile.write('\n')

然后我尝试了嵌套字典(下面的代码),但是我得到了错误“is not JSON serializable”

with open ("ETestjsonfile.json", "r") as myfile:
    Edgedata=myfile.read().replace('\n', '')
    print Edgedata

with open ("NTestjsonfile.json", "r") as myfile:
    Nodedata=myfile.read().replace('\n', '')
    print Edgedata

    Ndata = Nodedata
    Edata = Edgedata

    target = {'element': {'node': {Ndata}, 'edge': {Edata}}} 


print json.dumps(target, indent = 3)

f = open( 'DICTTEST.json', 'w' )
f.write(repr(target) + '\n' )
f.close()

Tags: csvidjsonsourcetargetdata节点open