Reputation: 5176
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
Reputation: 1813
Here one way to do it. The pattern \[(\d+?)\](.+)
works like this:
(…)
is a capture group. Just means whatever matches within the brackets will be a token in the result.\d
means a digit\d+
means a digit, one or more times\d+?
means a digit, one or more times, but as few as possibile before the pattern matches something else..+
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
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
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