1

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"
    }
  ]
}
3
  • is color;blue:36 ,red:27 really the format you want to convert? Commented Nov 20, 2016 at 18:24
  • yes..i get data in this format and im looking to convert it to the above format.. Commented Nov 20, 2016 at 18:31
  • do you have some more data? Commented Nov 20, 2016 at 18:32

3 Answers 3

1

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)

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

1 Comment

Ah you won the race! :)
1

This proposal splits the string first by semicolon for getting the type and the data, delimited by ' ,'. Then split by colon for data and total.

var data = 'color;blue:36 ,red:27',
    parts = data.split(';'),
    object = {
        Record: parts[1].split(' ,').map(function (a) {
            var p = a.split(':');
            return { type: parts[0], data: p[0], total: p[1] };
        })
    };

console.log(object);
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

you gave answer and i didn't even understand question
0

Here is how I'd do it

var dataFormat = "color;blue:36 ,red:27"
var splitFormat = dataFormat.split(";");
var type = splitFormat[0];
var colors = splitFormat[1].split(",");
var results = [];
_.each(colors, function(color) {
console.log(color)  
  var obj = {
    "type": type,
    "data": color.split(":")[0],
    "total":color.split(":")[1]
  }
  results.push(obj);
});
var final = {
  "Result": results
};
$("#result").html(JSON.stringify(final));
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="result"></div>

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.