Theodore K.
Theodore K.

Reputation: 5176

Convert string with index in brackets to JSON array

I have various strings with numbers in brackets like "[4]Motherboard, [25]RAM" how can I convert such a string to a JSON array (keeping both ids and values) like this:

{"data":[
  {"id":"4","item":"Motherboard"},
  {"id":"25","item":"RAM"}
]};

I'm tried using split(",") to create the array but I really can't find out how to get the inner data in this case.

Upvotes: 1

Views: 831

Answers (3)

tmslnz
tmslnz

Reputation: 1813

Here one way to do it. The pattern \[(\d+?)\](.+) works like this:

  1. (…) is a capture group. Just means whatever matches within the brackets will be a token in the result.
  2. \d means a digit
  3. \d+ means a digit, one or more times
  4. \d+? means a digit, one or more times, but as few as possibile before the pattern matches something else.
  5. .+ means any character, one or more times.

[ and ] have a special meaning in regular expression, so if you actually want to match the characters themselves, you need to escape them like so \[ and \].

The double backslashes \\ are just a JS oddity when defining a regex via a string as opposed to using a /literal/. Just two ways of saying the same thing.

There's plenty of resources to learn regex syntax, and http://regex101.com is a great place to play with patterns and experiment.

var input = "[4]Motherboard, [25]RAM";
var pattern = '\\[(\\d+?)\\](.+)';
var result = input.split(',').map(function (item) {
  var matches = item.match(new RegExp(pattern));
  return {id: matches[1], val: matches[2]};
});

console.log(result)

Upvotes: 2

Nina Scholz
Nina Scholz

Reputation: 386570

You could use a regular expression, which takes the number and the string, and assign it as property to an object.

var string = "[4]Motherboard, [25]RAM",
    data = string.split(', ').map(function (a) {
        var p = a.match(/^\[(\d+)\](.+)$/);
        return { id: p[1], item: p[2] };
    });
console.log(data);

Upvotes: 2

afuous
afuous

Reputation: 1498

function toArray(string) {
    return {
        data: string.split(",").map(function(str) {
            str = str.trim();
            return {
                id: str.substring(1, str.indexOf("]")),
                item: str.substring(str.indexOf("]") + 1),
            };
        }),
    };
}

Upvotes: 1

Related Questions