-2

I have a json string returned from a HTTP GET service that looks like this;

x=[{
    "value": 1.37,
    "date_transacted": "2015-01-01"
},
{
    "value": 1.62,
    "date_transacted": "2015-02-01"
},
{
    "value": 1.83,
    "date_transacted": "2015-03-01"
}]

I want to convert it to something that looks like this;

y=[{
    c: [{
        v: "2015-01-01"
    },
    {
        v: "1.37"
    }]
},
{
    c: [{
        v: "2015-01-02"
    },
    {
        v: "1.62"
    }]
},
{
    c: [{
        v: "2015-01-03"
    },
    {
        v: "1.83"
    }]
}]

How can this be done in javascript?

There is no need to give a complete coding answer as I am not looking to be spoon-fed. Some hints on where to get started will be useful as I am at a loss now.

EDIT: I asked a follow-up question after some preliminary work based on the hints provided by the answer to this question. How do I iterate over this json structure to produce another structure? The answer to this question is over there.

Community
  • 1
  • 1
guagay_wk
  • 26,337
  • 54
  • 186
  • 295
  • May I ask what is wrong with the question? Why the negative votes? If someone can explain, I can change the question accordingly. Sorry, what is obvious to you may not be obvious to me. – guagay_wk Oct 23 '15 at 07:53
  • 1
    Because it seems like you just tried nothing and you are waiting for someone coding that for you – Magus Oct 23 '15 at 07:54
  • Ok. I did try but it dpes appear to be so. Fair comment. Let me change the question accordingly. – guagay_wk Oct 23 '15 at 07:55

1 Answers1

1

Start by using JSON.parse(string) to convert the JSON string into a JavaScript object. See this answer.

In your case, you'll get an array of objects. Iterate over the array. For each object in it that looks like this...

{
    "value": 1.37,
    "date_transacted": "2015-01-01"
}

create a new object that looks like this...

{
    c: [{
        v: "2015-01-01"
    },
    {
        v: "1.37"
    }]
}

and push that new object into another array.

So now you've got the reformatted data in a JavaScript variable. If you want to convert it back to JSON, use JSON.stringify(object) as described here.

Community
  • 1
  • 1
jkdev
  • 11,360
  • 15
  • 54
  • 77
  • Thanks. It is a good start. I tried to work on this problem but don't know how to start. – guagay_wk Oct 23 '15 at 08:18
  • I did some preliminary work but still stuck at some point over iteration. Another follow-up question has been asked. https://stackoverflow.com/questions/33298774/how-do-i-iterate-over-this-json-structure-to-produce-another-structure – guagay_wk Oct 23 '15 at 09:17