Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active April 19, 2024 00:52
Show Gist options
  • Select an option

  • Save lewdev/594c148b9cd09d270cfd29b373ff5b85 to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/594c148b9cd09d270cfd29b373ff5b85 to your computer and use it in GitHub Desktop.
πŸ‘‰ Clean JSON Inputs & Validate

πŸ‘‰ Clean JSON Inputs & Validate

I keep receiving JSON data with odd characters so I made a small app that corrects all those issues and does an JSON.parse check to see if it passes. Parsing errors will display if any.

πŸ”– Bookmarklet (329b)

data:text/html,<h3>Clean JSON</h3><h5>Input</h5><textarea id=i></textarea><h5>Output</h5><textarea id=o></textarea><p id=err></p><script>i.onchange=_=>{o.value=v=i.value.replace(/[\u000B\u001C\u001D]/g, "").replace(/\u0019/g,"'").replace(/\u0013/g, "-");try{JSON.parse(v);err.innerHTML="Valid"}catch(e){err.innerHTML=e}}</script>

πŸ‘¨β€πŸ’» Clean Version

<h3>Clean JSON</h3>

<h5>Input</h5>
<textarea id=i></textarea>

<h5>Output</h5>
<textarea id=o></textarea>

<p id=err></p>

<script>
i.onchange = _ => {
  o.value = v = i.value
    .replace(/[\u000B\u001C\u001D]/g, "") //weird space characters like tab
    .replace(/\u0019/g,"'") //odd single quote character 
    .replace(/\u0013/g, "-") //odd dash character
  ;
  try {
    JSON.parse(v);
    err.innerHTML = "Valid";
  }
  catch (e) {
    err.innerHTML = e;
  }
};
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment