1

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.

1
  • 4
    Go with the obvious solution and let us know what have you tried.. Commented Nov 9, 2016 at 9:47

3 Answers 3

2

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

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

1 Comment

This does not match the format in the question. You have { "4": "Motherboard" }, but it asks for { "id": "4", "item": "Motherboard" }.
2

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)

1 Comment

Good one but can you please explain the regex a bit? I know it's a simple case, but still...
1
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),
            };
        }),
    };
}

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.