{
"cells": [
{
"cell_type": "markdown",
"metadata": {},
"source": [
"\n# JavaScript\n\nExample of writing JSON format graph data and using the D3 JavaScript library\nto produce an HTML/JavaScript drawing.\n\nYou will need to download the following directory:\n\n- https://github.com/networkx/networkx/tree/main/examples/external/force\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"metadata": {
"collapsed": false
},
"outputs": [],
"source": [
"import json\n\nimport flask\nimport networkx as nx\n\nG = nx.barbell_graph(6, 3)\n# this d3 example uses the name attribute for the mouse-hover value,\n# so add a name to each node\nfor n in G:\n G.nodes[n][\"name\"] = n\n# write json formatted data\nd = nx.json_graph.node_link_data(G) # node-link format to serialize\n# write json\njson.dump(d, open(\"force/force.json\", \"w\"))\nprint(\"Wrote node-link JSON data to force/force.json\")\n\n# Serve the file over http to allow for cross origin requests\napp = flask.Flask(__name__, static_folder=\"force\")\n\n\n@app.route(\"/\")\ndef static_proxy():\n return app.send_static_file(\"force.html\")\n\n\nprint(\"\\nGo to http://localhost:8000 to see the example\\n\")\napp.run(port=8000)"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.7"
}
},
"nbformat": 4,
"nbformat_minor": 0
}
Generated by dwww version 1.16 on Wed Apr 8 10:57:54 CEST 2026.