Skip to content

Instantly share code, notes, and snippets.

@atomjoy
Created January 17, 2025 14:45
Show Gist options
  • Save atomjoy/a8177e0512eafeefecc63744960f7fb9 to your computer and use it in GitHub Desktop.
Save atomjoy/a8177e0512eafeefecc63744960f7fb9 to your computer and use it in GitHub Desktop.
Code to json
function jsonEscape(str) {
return str.replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
}
function jsonEscapeCode(str) {
return str.replace(/"/g, '\\"').replace(/'/g, "\'");
}
let code = jsonEscapeCode(`<?php
$name = "Benny's";
echo "Sometext \${name}";
echo 'Second line ' . $name . ' text';
?>`)
let data = `{"count" : 1, "stack" : "${code}"}`;
console.log(jsonEscape(data));
let obj = JSON.parse(jsonEscape(data));
console.log(obj.stack);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment