graph.json

node_link_graph.

node_link_graph reads the sample JSON. Create it if needed. NetworkX 3 wants edges='links'.

Goal

Print nodes loaded from JSON.

from pathlib import Path
Path('graph.json').write_text('{"directed": false, "multigraph": false, "graph": {}, "nodes": [{"id": "Nairobi"}, {"id": "Nakuru"}], "links": [{"source": "Nairobi", "target": "Nakuru", "km": 160}]}\n', encoding='utf-8')
print('wrote')
import json
from pathlib import Path
import networkx as nx
data = json.loads(Path('graph.json').read_text(encoding='utf-8'))
try:
    G = nx.node_link_graph(data, edges='links')
except TypeError:
    G = nx.node_link_graph(data)
print(list(G.nodes()))
print(list(G.edges(data=True)))
import json
from pathlib import Path
print(json.loads(Path('graph.json').read_text(encoding='utf-8'))['nodes'])
import networkx as nx
print(nx.Graph([('Nairobi', 'Nakuru')]).order())