Deepak Desai Deepak Desai - 12 days ago 6
JSON Question

how to change the below format to json format using javascript

I want to convert this data format:

"color;blue:36 ,red:27"


to the following JSON format:

{
"Record": [
{
"type": "color",
"data": "blue",
"total": "36"
},
{
"type": "color",
"data": "red",
"total": "27"
}
]
}

Answer

It's hard to understand the exact problem with the given input, but that should suffice:

    var input = "color;blue:36 ,red:27";

    // Reassignment is bad, but will shorten the example
    input = input.split(";");

    var attributeName = input[0];

    // No length validations, also bad
    var attributes = input[1].split(",");

    var results = {"Record": attributes.map(function(a) {
        a = a.split(":");
        return {"type":attributeName,
            "data":a[0].trim(),
            "total": a[1].trim()}
    })};

    console.log(results)

Comments