简体   繁体   中英

How to convert graph json file to graph adjacency list file in python?

I have json file for graph in python and I would like to parse it and write it as adjacency list file as follows. Would someone can help me with that?

A B
C A
D Z

where fist and second column are the nodes. I don't have experience with .json file and here is how my json file looks like for graph.

   "edges": [
            {
                "data": {
                    "cost": 0.01,
                    "source": "HBA2",
                    "target": "HBB"
                }
            },
            {
                "data": {
                    "cost": 0.598835,
                    "source": "HBA2",
                    "target": "EGFR"
                }
            },
            {
                "data": {
                    "cost": 0.594442,
                    "source": "HBA2",
                    "target": "DAXX"
                }
            },
            {
                "data": {
                    "cost": 0.598835,
                    "source": "HBA2",
                    "target": "PBK"
                }
            },
            {
                "data": {
                    "cost": 0.598835,
                    "source": "HBA2",
                    "target": "MAPK14"
                }
            },
            {
                "data": {
                    "cost": 0.598835,
                    "source": "HBA2",
                    "target": "MST4"
                }
            },
#! /usr/bin/env python3

import json


def get_edges(graph):
    for d in json.loads(graph):
        node = d['data']
        yield node['source'], node['target']


def plot(graph, outfile='graph.txt'):
    with open(outfile, 'w') as fout:
        for src, dst in get_edges(graph):
            fout.write('%s  %s\n' % (src, dst))


if __name__ == '__main__':
    plot('''
[ { "data": { "cost": 0.010000, "source": "HBA2", "target": "HBB" }},
  { "data": { "cost": 0.598835, "source": "HBA2", "target": "EGFR" }},
  { "data": { "cost": 0.594442, "source": "HBA2", "target": "DAXX" }},
  { "data": { "cost": 0.598835, "source": "HBA2", "target": "PBK" }},
  { "data": { "cost": 0.598835, "source": "HBA2", "target": "MAPK14" }},
  { "data": { "cost": 0.598835, "source": "HBA2", "target": "MST4" }}
]''')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM