0

I am trying to read json file using D3 library but when i try to read json i get alert Null Values (here i am using alert).

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
d3.json( "file.json", function( json ) {
  alert( "JSON Data: " + json );
});
</script>
</html>

Following is file.json (which is already validated online)

 [{
        "sets": [0],
        "size": 1958
    },
    {
        "sets": [1],
        "size": 1856
    },
    {
        "sets": [2],
        "size": 1297
    },
    {
        "sets": [0, 1],
        "size": 220
    },
    {
        "sets": [2, 0],
        "size": 123
    },
    {
        "sets": [2, 1],
        "size": 139
    }
 ]

How can i fix such issue?

man data
  • 43
  • 2
  • 8

2 Answers2

0

If you are running in a browser you can't load local files. I suggest uploading the data somewhere online, like here and then request it with d3.json().

Likeso:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
d3.json( "https://gist.githubusercontent.com/kvyb/d482dc15602c34841d4796daa9ed64cb/raw/d737e19c03868adf2f15103fcd98384f4c364785/file.json", function(json) {
  alert( "JSON Data: " + json)
});
</script>
</html>

Otherwise you can hardcode it into your html file:

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>Simple venn.js example</title>
</head>

<body>
    <div id="weighted_example"></div>
</body>

<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://d3js.org/d3.v4.min.js"></script>

<script>
var json =  [{
        "sets": [0],
        "size": 1958
    },
    {
        "sets": [1],
        "size": 1856
    },
    {
        "sets": [2],
        "size": 1297
    },
    {
        "sets": [0, 1],
        "size": 220
    },
    {
        "sets": [2, 0],
        "size": 123
    },
    {
        "sets": [2, 1],
        "size": 139
    }
 ]

alert( "JSON Data: " + json)

</script>
</html>

If you don't mind using other libraries, there is a jquery solution to loading locally, among others.

Kristian Vybiral
  • 509
  • 9
  • 20
0

In order to get these files to work locally you will need to use an HTTP server. Personally I use MAMP for Mac machine.