From 41c1b4e38e9c9c21145e78aa490a22376c2e7f85 Mon Sep 17 00:00:00 2001 From: Tahsin Date: Sun, 21 Aug 2022 14:55:09 +0700 Subject: [PATCH] Add script to remove escape characters from JSON string --- Scripts/UnescapeJSON.js | 47 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Scripts/UnescapeJSON.js diff --git a/Scripts/UnescapeJSON.js b/Scripts/UnescapeJSON.js new file mode 100644 index 00000000..cc9796a6 --- /dev/null +++ b/Scripts/UnescapeJSON.js @@ -0,0 +1,47 @@ +/** + { + "api":1, + "name":"Unescape JSON String", + "description":"Removes escape characters from JSON string", + "author":"tahsinature", + "icon":"table", + "tags":"json,unescape,escape" + } +**/ + +const unescapeJSONString = (str = "") => { + return str + .replace(/(\\n)/g, "") + .replace(/(\\r)/g, "") + .replace(/(\\t)/g, "") + .replace(/(\\f)/g, "") + .replace(/(\\b)/g, "") + .replace(/(\")/g, '"') + .replace(/("{)/g, "{") + .replace(/(}")/g, "}") + .replace(/(\\)/g, "") + .replace(/(\/)/g, "/"); +}; + +function main(state) { + let input = state.fullText; + try { + try { + JSON.parse(input); + } catch (error) { + if (!input.startsWith('"')) input = `"${input}`; + if (!input.endsWith('"')) input = `${input}"`; + JSON.parse(input); + } + + state.fullText = unescapeJSONString(input); + state.postInfo("JSON is unescapped!"); + } catch (error) { + let msg = "Something went wrong!"; + + if (error instanceof SyntaxError) msg = "Invalid JSON"; + else msg = `${error.name}-${error.message}`; + + state.postError(msg); + } +}