Loading and using JSON for Cytoscape.js
Asked Answered
C

2

9

Context

I want to use cytoscape.js for visualizing graphs. While I am capable with a myriad of languages (C++, Mathematica, R, etc), I am new to Javascript, JSON, HTML, and CSS. Thus it would be favorable to learn these languages through this use case (implementing graphs with cytoscape.js). Please keep this in mind in your answer.

I have previously asked how to [remotely load cytoscape.js and how to get graphs display (requires a div). Since then I have created a script that turns a graph as represented in one of the other languages I use, into the JSON format indicated here. While I can just copy-paste all of this directly into my program, for large networks that is clearly a poor way to implement it. An example of my script's output is at the bottom of this.

Question

Given a JSON object/file(?) how can I do the following:

  • load it into cytoscape.js without copy-pasting the code.
  • referencing it once loaded. (e.g. basic explanation of how JSON syntax for use in cytoscape.js)

Script Output

cytoscape({

container: document.getElementById('cy'),

elements: [ 
{// node Node 1
    group: 'nodes',

    data: {
        id: 'Node 1'
    },

    selected: false,

    selectable: true,

    locked: false,

    grabbable: true,

    selectable: true,

},
{// node Node 2
    group: 'nodes',

    data: {
        id: 'Node 2'
    },

    selected: false,

    selectable: true,

    locked: false,

    grabbable: true,

    selectable: true,

},
{// node Node 3
    group: 'nodes',

    data: {
        id: 'Node 3'
    },

    selected: false,

    selectable: true,

    locked: false,

    grabbable: true,

    selectable: true,

},
{// edge 1_2
    group: 'edges',

    data: {
        id: '1_2',
        source: '1',
        target: '2'
    }
},
{// edge 2_3
    group: 'edges',

    data: {
        id: '2_3',
        source: '2',
        target: '3'
    }
},
{// edge 3_1
    group: 'edges',

    data: {
        id: '3_1',
        source: '3',
        target: '1'
    }
}
],
style: [
    {
        selector: 'node',
        style: {
            'content': 'data(id)'
        }
    }
]

});
Clairvoyance answered 29/10, 2016 at 9:19 Comment(0)
C
11

<head>
    <title></title>
    <script src="js/vendor/cytoscape.min.js"></script>
    <script src="js/vendor/jquery.min.js"></script>
</head>

<style>
    #cy {
        width: 100%;
        height: 100%;
        position: absolute;
        top: 0px;
        left: 0px;
    }
</style>

<body>
    <div id="cy"></div>
    <script>
        $.getJSON("cyto.js", function (data) {
            //console.log(data);
            var cy = cytoscape({
                container: document.getElementById('cy'),
                elements: data,
                style: [
                    {
                        selector: 'node',
                        style: {
                            'label': 'data(label)',
                            'width': '60px',
                            'height': '60px',
                            'color': 'blue',
                            'background-fit': 'contain',
                            'background-clip': 'none'
                        }
                    }, {
                        selector: 'edge',
                        style: {
                           'text-background-color': 'yellow',
                            'text-background-opacity': 0.4,
                            'width': '6px',
                            'target-arrow-shape': 'triangle',
                            'control-point-step-size': '140px'
                        }
                    }
                ],
                layout: {
                    name: 'circle'
                }
            });
        });
    </script>
</body>

in cyto.js you can input valid JSON data, for example

  {
    "nodes": [
            {
            "data": {"id": "a", "label": "Gene1"}
            },
            {
            "data": {"id": "b", "label": "Gene2"}
            },
            {
            "data": {"id": "c", "label": "Gene3"}
            },
            {
            "data": {"id": "d", "label": "Gene4"}
            },
            {
            "data": {"id": "e", "label": "Gene5"}
            },
            {
            "data": {"id": "f", "label": "Gene6"}
            }
    ],
            "edges": [
            {
            "data": {
            "id": "ab",
                    "source": "a",
                    "target": "b"
            }
            },
            {
            "data": {
            "id": "cd",
                    "source": "c",
                    "target": "d"
            }
            },
            {
            "data": {
            "id": "ef",
                    "source": "e",
                    "target": "f"
            }
            },
            {
            "data": {
            "id": "ac",
                    "source": "a",
                    "target": "d"
            }
            },
            {
            "data": {
             "id": "be",
                    "source": "b",
                    "target": "e"
                }
                }]    
    }
Corinnacorinne answered 19/12, 2016 at 10:8 Comment(1)
Neat example; run on webserver (e.g. http-server) to avoid CORS issue when running on local host.Giacinta
G
0

Let's presume you have a json file in the same folder as your 'index.html', and your server is running. First request the json file via a http request (using plain javascript or jquery ).

If your json file has the same format as the elements properties, you can just parse it to a javascript object and set it. E.g.

var myObject = {};
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
  if (this.readyState == 4 && this.status == 200) {
      myObject = JSON.parse(this.responseText);
      initCytoscape();
  }
};
xhttp.open("GET", "myJson.json", true);
xhttp.send();

function initCytoscape() {
  cytoscape({
    container: document.getElementById('cy'),
    elements: myObject
  });
}

if the json property is different than cytoscape's format, then you have to programatically convert it.

Gastrocnemius answered 30/10, 2016 at 0:54 Comment(2)
I have a lot of questions, but could you possibly walk me through how this works?Clairvoyance
If you use the fetch() API, you can just specify elements: fetch('./my-dir/myfile.json'), since Cytoscape accepts promises for your dataCompline

© 2022 - 2024 — McMap. All rights reserved.