0

I have a JSON string which looks like this:

[
    {
        "queryResult": {
            "A": "12-04-2014",
            "B": 1
        }
    },
    {
        "queryResult": {
            "A": "13-04-2014",
            "B": 2
        }
    },
    {
        "queryResult": {
            "A": "14-04-2014",
            "B": 3
        }
    }
]

And I need to parse it and change it to this

[
    {
        "A": "12-04-2014",
        "B": 1
    },
    {
        "A": "13-04-2014",
        "B": 2
    },
    {
        "A": "14-04-2014",
        "B": 3
    }
]

I already have a function for making that change, which is:

function justAnExample() {
    var jsonData = exampleJSON(); //Obtains the JSON
    var finalJSON=JSON.stringify(jsonData[0]['queryResult']);
    for (var i = 1; i < jsonData.length; i++) {
        finalJSON = finalJSON+','+JSON.stringify(jsonData[i]['queryResult']);
    }
    return JSON.parse('[' + finalJSON + ']');
}

But, this method uses stringifying and then parsing JSON to recreate the JSON object, which works, but is there a better solution, in which I can work with the object notation itself.

P.S: I know the term "JSON object" is a semi-pseudo thing, and that only the JSON notation/format matters, but, just need to confirm if this is the proper way to do it.

Edit

Please find a JS fiddle for the problem

http://jsfiddle.net/mukilr/uJV54/

5
  • Does your "JSON string" look exactly like you have shown? Commented May 21, 2014 at 6:45
  • Yes, this is the exact representation. Commented May 21, 2014 at 6:46
  • Can you please create a jsfiddle with that exact string? Commented May 21, 2014 at 6:47
  • jsfiddle.net/mukilr/uJV54 Commented May 21, 2014 at 6:54
  • @thefourtheye The fiddle is done Commented May 21, 2014 at 6:54

1 Answer 1

2

You can do:

var json = [
    {
        "queryResult": {
            "A": "12-04-2014",
            "B": 1
        }
    },
    {
        "queryResult": {
            "A": "13-04-2014",
            "B": 2
        }
    },
    {
        "queryResult": {
            "A": "14-04-2014",
            "B": 3
        }
    }
];

var out = [];


for (var i = 0; i < json.length; i++){
out[i] = json[i].queryResult;
}

check this fiddle

EDIT This is your fiddle updated

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.