JSON.parse method
The most common solution to convert string to object in JavaScript would be to use the native JSON.parse method.
Example:
const stringToConvert = '{"firstName": "John", "lastName": "Doe"}';
const converted = JSON.parse(stringToConvert);
console.log(converted);
// {
// firstName: "John",
// lastName: "Doe"
// }
JSON.parse only works with a valid json string. If you try to use it with a string that is not in json format, you will get an error:
JSON.parse('firstName: "John", lastName: "Doe"');
// Uncaught SyntaxError: Unexpected token 'i', "firstName: "… is not valid JSON
JSON.parse reviver
JSON.parse(input: string, [reviver: fn(key, value): any]);
- input: string, should be a valid json string
- reviver: optional function that transforms the parsed value of each key-value pair
Reviver usage example:
const input = '{"first": 10,"second": 80}';
function reviver(key, value) {
if (key === 'first') return value * 8;
else return value;
}
console.log(JSON.parse(input, reviver));
// {
// "first": 80,
// "second": 80
// }
Important note: the last value passed to reviver callback as an argument will be the resulting root object itself, so be careful.
Please refer to MDN for more info.
Handling errors
If the input string is not a valid json, JavaScript will throw an error.
If this is not the desired behavior, simply wrap it with a try/catch block:
const input = "firstName: John, lastName: Doe";
let result = {};
try {
result = JSON.parse(input);
} catch {
// silence
}
Converting string to an object manually
If your input string is not in json format, you can create your own function to handle this case. Here are a few working examples:
Key-value pairs case
const inputString = "firstName: John, lastName: Doe";
function convertStringToObject(input) {
let result = {};
// first we want to split each key-value pair
// into a separate varialbe
const pairs = input.split(", ");
// then, using the same technique, we can separate
// key from value
for (const item of pairs) {
const keyValue = item.split(": ");
// in the resulting array key will be under index "0"
// while value is the item under index "1"
result[keyValue[0]] = keyValue[1];
}
return result;
}
Value-following-key case
A little bit more tricky case, but the solution is pretty easy once you understand how it works:
const inputString = "firstName, John, lastName, Doe";
function convertStringToObject(input) {
let result = {};
const items = input.split(", ");
items.forEach((item, index) => {
// if index is even, the current item is a "key" and we wanna skip this step
if (index % 2 !== 1) return;
// otherwise the current item is a "value" and we wanna put it
// in an appropriate field of the "results" object
// and the key field equals to the current index - 1
result[items[index - 1]] = item;
});
return result;
}
Combining JSON.parse with the manual approaches
If you not sure will your object be a valid json format, or some other certain format, you can use a runtime hack to get the correct value from the input string:
const inputString = "firstName, John, lastName, Doe";
let result = {};
function convertStringToObject(input) {
...
return result;
}
try {
result = JSON.parse(inputString);
} catch {
result = convertStringToObject(inputString);
}
How to convert String to Object
What if you need the vice-versa operation – convert string to object in js? The solution is JSON.stringify, and there is no room for complexity. Any javascript string or other variables could be converted to json this way.
Example:
const objectToConvert = {
firstName: "Jane",
lastName: "Doe"
}
const converted = JSON.stringify(objectToConvert);
console.log(converted)
// '{"firstName":"Jane","lastName":"Doe"}'
Hope you found some of the tips helpful. Happy coding!
- Learn more about JSON.parse: MDN
- Read about Array methods: W3Schools
- Try/Catch in JavaScript: Javascript.info