Created
May 6, 2024 12:35
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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