1

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

3
  • {"key":"1", "value","description 1"} not valid Commented Dec 8, 2016 at 11:43
  • That isn't JSON. Commented Dec 8, 2016 at 11:46
  • @Quentin LoL. Now this is new. I know there isn't a JSON Object. Commented Dec 8, 2016 at 11:47

3 Answers 3

1

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);

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

Comments

0

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.

6 Comments

Man, too bad, without an explanation?
Still, no idea what you are doing! The regex is crazy, plus many (including me) don't know how arrow and spread functions work.
And don't you think using RegEx for such a small thing could be so cumbersome and overkill?
neat ! :) you could use the destruction variables direcly.
even shorter str.replace(/(.+?),(.+?)(;|$)/g, (_, key, value) => data.push({key, value}));
|
0

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);

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.