Last active
June 28, 2024 12:48
-
-
Save craigsdennis/0f00869fe2e2f2da9d6287984c62b2af to your computer and use it in GitHub Desktop.
Convert Python String to JSON
This file contains 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
// Thanks ChatGPT! | |
// Getting back a Python dictionary in JavaScript, and need it to be JSON | |
function pythonDictToJson(pythonDictString) { | |
// Regular expression to match and replace Python literals | |
const regex = /('(\\'|[^'])*')|None|True|False/g; | |
// Replacer function to handle each match | |
const replacer = (match) => { | |
if (match === 'None') { | |
return 'null'; | |
} else if (match === 'True') { | |
return 'true'; | |
} else if (match === 'False') { | |
return 'false'; | |
} else { | |
// Return string matches unaltered | |
return match; | |
} | |
}; | |
// Replace Python literals with JSON equivalents | |
let jsonString = pythonDictString.replace(regex, replacer); | |
// Replace single quotes with double quotes outside of strings | |
jsonString = jsonString.replace(/([^\\])'/g, '$1"'); | |
// Parse the string to a JSON object | |
let jsonObject; | |
try { | |
jsonObject = JSON.parse(jsonString); | |
} catch (error) { | |
console.error("Error parsing JSON string:", error); | |
return null; | |
} | |
return jsonObject; | |
} | |
// Example usage | |
let pythonDictString = "{'key1': 'value1', 'key2': 2, 'key3': None, 'key4': True, 'key5': False, 'key6': 'Example: True, False, None'}"; | |
let jsonObject = pythonDictToJson(pythonDictString); | |
console.log(jsonObject); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment