2

I'm using the Graphite Render API to return data in JSON format to node.js, which I'd like to pass to Rickshaw for graphing. I'm using grockets.js to pass the data to the client via socket.io. I have tested Rickshaw with socket.io successfully by passing manual data using one of their examples. The issue I have is that the JSON format Graphite returns is not what Rickshaw is expecting and I'm not sure how to go about converting it.

The graphite output looks like so:

[
    {
        "target": "localhost_localdomain.cpu-0.cpu-idle", 
        "datapoints": [
        [99.999698, 1392728820],
        [100.000898, 1392728880],
        [99.999968, 1392728940],
        [99.299848, 1392732360]
        ]
    }
]

I need it to be in this format:

[
    {
        "target": "localhost_localdomain.cpu-0.cpu-idle", 
        "datapoints": [
        { "x": 99.999698, "y": 1392728820 },
        { "x": 100.000898, "y": 1392728880 },
        { "x": 99.999968, "y": 1392728940 },
        { "x": 99.299848, "y": 1392732360 }
        ]
    }
]

Am I right in saying this is an array of objects? Any help or guidance would be really appreciated!

Thanks!

user2576960
  • 2,883
  • 2
  • 14
  • 10

1 Answers1

2

Given that it's just the datapoints that needs to be transformed, this should be fairly easy:

var myData = [{
    "target": "localhost_localdomain.cpu-0.cpu-idle",
        "datapoints": [
        [99.999698, 1392728820],
        [100.000898, 1392728880],
        [99.999968, 1392728940],
        [99.299848, 1392732360]
    ]
}];

var transformedPoints = myData[0].datapoints.map(function (pt) {
    return {
        x: pt[0],
        y: pt[1]
    };
});

myData[0].datapoints = transformedPoints;

console.log(myData);

Here's a fiddle

Matt Burland
  • 44,552
  • 18
  • 99
  • 171
  • Thanks for the prompt response Matt, that's exactly what I'm after. However for some reason myData[0].datapoints.map shows as undefined when I run that....Any idea why that would be? I've logged myData to console to double check it's in the format I've described and it looks the same as your fiddle, which is odd. – user2576960 Feb 18 '14 at 17:59
  • 1
    Ok so I think it's because it's being passed within the function as a string rather than an object so I'm unable to map it. Should I be able to fix this through something like JSON.parse? – user2576960 Feb 18 '14 at 18:48
  • @user2576960: Yeah, `JSON.parse` should do it. – Matt Burland Feb 18 '14 at 18:58