JavaScript - convert string to object
How to convert string to object in JavaScript?
Let's say I have the following string:
var text = 'id:1, name:Kate';
and I need to convert it to:
var object = { id: 1, name: 'Kate' };
Solution 1
Assuming that your text
is JSON string:
var text = '{"id":"1", "name":"Kate"}';
You can use JSON.parse()
method:
// ONLINE-RUNNER:browser;
var text = '{"id":"1", "name":"Kate"}';
var object = JSON.parse(text);
console.log(object.id); // 1
console.log(object.name); // Kate
Solution 2
For a custom string in your case you can use split()
method with a simple for
loop to add properties to an empty object:
// ONLINE-RUNNER:browser;
var text = 'id:1, name:Kate';
var parts = text.split(', ');
var object = {};
for (var i = 0; i < parts.length; ++i) {
var tmp = parts[i].split(':');
object[tmp[0]] = tmp[1];
}
console.log(object.id); // '1'
console.log(object.name); // 'Kate'
Note:
This solution will give you property values as strings, even if they are booleans, numbers, etc. (e.g
'1'
instead of1
).
Note:
This solution assumes there are no '
:
' characters in the property name and value.
References
Here is a solution that splits the text
into parts
, removing whitespace. Then creates key/value pair
for each part
(also omitting whitespace). In next step it checks for duplicate keys because objects cannot have duplicated properties. At the end it creates the result
object.
// ONLINE-RUNNER:browser;
var PART_EXPRESSION = /\s*,\s*/;
var PAIR_EXPRESSION = /\s*:\s*/;
function parseText(text) {
var parts = text.split(PART_EXPRESSION);
var object = {};
for (var i = 0; i < parts.length; ++i) {
var part = parts[i];
if (part) {
var pair = part.split(PAIR_EXPRESSION);
var key = pair[0];
if (key in object) {
throw new Error('Text contains duplicated keys.');
}
var value = '';
if (pair.length > 0) {
value += pair[1];
for (var j = 2; j < pair.length; ++j) {
value += ':' + pair[j];
}
}
object[key] = value;
}
}
return object;
}
// Usage example:
var text = 'id:1, name:Kate:5, age:29';
var object = parseText(text);
console.log(object.id);
console.log(object.name);
console.log(object.age);