Skip to content

Instantly share code, notes, and snippets.

@amitasaurus
Created May 6, 2024 12:35
Show Gist options
  • Save amitasaurus/6d757c1fbf0164680b3ce6c6d8817e60 to your computer and use it in GitHub Desktop.
Save amitasaurus/6d757c1fbf0164680b3ce6c6d8817e60 to your computer and use it in GitHub Desktop.
Write a function to convert json string to js object in javascript without using JSON.parse
function parseJSON(jsonString: string): Record<string, any> {
const result: Record<string, any> = {};
jsonString = jsonString.substring(1, jsonString.length - 1);
const pairs = jsonString.split(',');
for (const pair of pairs) {
const keyValue = pair.split(':');
let key = keyValue[0].trim();
let value = keyValue[1].trim();
key = key.substring(1, key.length - 1);
value = value.substring(1, value.length - 1);
result[key as string] = value;
}
return result;
}
console.log(parseJSON('{"name": "John", "age": "25"}'));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment