Albertus
Albertus

Reputation: 101

String to JSON format in javascript

I want to create json format from variable javascript.

var code="1,description 1;2,description 2;3,description 3;4,description 4";

I want to change to JSON Format become:

var result = [{"key":"1", "value","description 1"},{"key":"2", "value","description 2"},{"key":"3", "value","description 3"},{"key":"4", "value","description 4"} ]

I already using split but too difficult because use 2 split(split by "," and ";"). How to fix it?

Thank you.

Regards, Bobby

Upvotes: 1

Views: 73

Answers (3)

georg
georg

Reputation: 214959

When parsing stuff in Javascript you usually make a regex that represents one data item and globally replace it with a function that populates some structure and pushes it into a collection:

let data = [];

let str = "1,description 1;2,description 2;3,description 3;4,description 4";

str.replace(/(.+?),(.+?)(;|$)/g, (_, key, value) => data.push({key, value}));

console.log(data)

The reason of (ab)using .replace for this is that global .match doesn't support groups.

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386604

You could map the splitted parts with a new object for the key and value properties.

var code="1,description 1;2,description 2;3,description 3;4,description 4",
    result = code.split(';').map(function (a) {
        var p = a.split(',');
        return { key: p[0], value: p[1] };
    });

console.log(result);

Upvotes: 0

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167182

Note, it should be:

{"key":"1", "value": "description 1"}

You need to use multiple loops. And the process is:

  1. Define final object.
  2. Step one: Split on ;.
  3. Step two: Split each of the element on ,.
  4. Push everything to the final object.

Snippet

// Define final object:
var finalArray = [];
var code = "1,description 1;2,description 2;3,description 3;4,description 4";
// Step one: Split on ;
code = code.split(";");
// Step two: Split on ,
for (var i = 0; i < code.length; i++) {
  code[i] = code[i].split(",");
  finalArray.push({
    "key": code[i][0],
    "value": code[i][1]
  });
}
// Let's see the output:
console.log(finalArray);

Upvotes: 1

Related Questions