Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to load a json object instead of json file [duplicate]

Tags:

json

d3.js

I am trying to build a web project where I get details in JSON format, for example:

{
    "file_id": 333, 
    "t": "2016-03-08 12:00:56"
}

I was trying to show the output in d3 js bar chart. The problem I am facing is the code I've got is working for a JSON file but not for an object deserialized from the JSON. Can any one help me out with this?

The part of the working script for JSON file is this:

d3.json("FILENAME", function(error, data) {
    data = JSON.parse(data);
    x.domain(data.map(function(d) { return d.letter }));
    y.domain([0, d3.max(data, function(d) { return d.frequency })]);

If I change the filename to an object its not working.

like image 962
monic Avatar asked Mar 10 '16 07:03

monic


People also ask

Can a JSON object contain duplicate keys?

I've done some research and I understood that "duplicate" keys in JSON are legal, but different parsers act differently in handling this. How can I avoid the use of duplicate keys or, alternatively, make sure the schema validates the value for all duplicated keys? Hermann.

What does '@' mean in JSON?

It has no special meaning to JSON. This particular data uses it as a key string.

How read data from JSON file and convert it to a JavaScript object?

Use the JavaScript function JSON.parse() to convert text into a JavaScript object: const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}'); Make sure the text is in JSON format, or else you will get a syntax error.


1 Answers

being a JS library D3 works with the JS objects(along with other JS data types) only, d3.json is just a method to load the object from an external file. So if you dont need to load data from external file then dont use d3.json

//d3.json("FILENAME", function(error, data) {
    //data = JSON.parse(data);
    var data = {
        "file_id": 333, 
        "t": "2016-03-08 12:00:56"
    }; //your own object
    x.domain(data.map(function(d) { return d.file_id}));
    y.domain([0, d3.max(data, function(d) { return d.t})]);

hope it helps

like image 56
panghal0 Avatar answered Sep 18 '22 14:09

panghal0