Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Convert the number or boolean type JSON object from string type to its original in JavaScript
Suppose we have a JSON object where numeric and boolean values are stored as strings:
const obj = {"name":"sam","age":"24","isMarried":"false"};
console.log(obj);
{ name: 'sam', age: '24', isMarried: 'false' }
Here, the age property should be a number and isMarried should be a boolean. Our goal is to write a function that converts these string values back to their correct data types.
Method 1: Using parseInt and Boolean Conversion
This approach checks each property and converts numeric strings to numbers and boolean strings to booleans:
const obj = {
"name":"sam",
"age":"24",
"isMarried":"false"
};
const convertToOriginal = (obj = {}) => {
const keys = Object.keys(obj);
for(let i = 0; i
{ name: 'sam', age: 24, isMarried: false }
Method 2: Using JSON.parse for Type Conversion
A more robust approach using JSON.parse to handle type conversion safely:
const obj2 = {
"name":"john",
"age":"30",
"score":"95.5",
"isActive":"true",
"isVerified":"false"
};
const convertTypes = (obj) => {
const converted = {};
for(const key in obj) {
const value = obj[key];
try {
// Try to parse as JSON (handles numbers, booleans, null)
const parsed = JSON.parse(value);
// If parsing succeeds and it's not a string, use the parsed value
converted[key] = (typeof parsed !== 'string') ? parsed : value;
} catch {
// If parsing fails, keep original string value
converted[key] = value;
}
}
return converted;
};
const result = convertTypes(obj2);
console.log(result);
console.log("Types:", typeof result.age, typeof result.score, typeof result.isActive);
{ name: 'john', age: 30, score: 95.5, isActive: true, isVerified: false }
Types: number number boolean
Comparison
| Method | Handles Floats | Handles Edge Cases | Complexity |
|---|---|---|---|
| parseInt + Boolean | No | Limited | Simple |
| JSON.parse | Yes | Better | More robust |
Handling Edge Cases
const edgeCases = {
"zero": "0",
"negative": "-15",
"float": "3.14",
"nullValue": "null",
"emptyString": "",
"text": "hello"
};
const safeConvert = (obj) => {
const result = {};
for(const key in obj) {
const value = obj[key];
// Skip empty strings
if(value === "") {
result[key] = value;
continue;
}
try {
const parsed = JSON.parse(value);
result[key] = parsed;
} catch {
result[key] = value;
}
}
return result;
};
console.log(safeConvert(edgeCases));
{
zero: 0,
negative: -15,
float: 3.14,
nullValue: null,
emptyString: '',
text: 'hello'
}
Conclusion
Use JSON.parse for robust type conversion as it handles numbers, booleans, and null values correctly. For simple cases, manual parsing with parseInt and boolean checks works fine.
Advertisements
