Go based JSON Escape/Unescape

9,996 views
Skip to first unread message

Tong Sun

unread,
Aug 13, 2017, 11:35:41 PM8/13/17
to golang-nuts
Has anyone done Go based JSON Escape/Unescape yet? 

I want to pass any arbitrary content as a JSON string:

  {
      "content": "my escaped strings {\n         \"employees\": {\n             \"employee\": [\n                 {\n                     \"id\": \"1\",..."
  }

In order to pass a JSON string inside another JSON string in such a scenario, you need to escape it (e.g. manually via JSON Escape/Unescape).

 
Is there a Go package ready-made for it somewhere? 
Else, what are to be escaped so that I can embed any arbitrary content as a JSON string?

Thx


dja...@gmail.com

unread,
Aug 14, 2017, 12:28:36 AM8/14/17
to golang-nuts
may be it is by default ?

Tong Sun

unread,
Aug 14, 2017, 12:56:06 AM8/14/17
to golang-nuts
Oh, yeah, true. Thx a lot. 

BTW, I found the rule on what are to be escaped so that I can embed any arbitrary content as a JSON string:

The following characters are reserved in JSON and must be properly escaped to be used in strings:
  • Backspace is replaced with \b.
  • Form feed is replaced with \f.
  • Newline is replaced with \n.
  • Carriage return is replaced with \r.
  • Tab is replaced with \t.
  • Double quote is replaced with \"
  • Backslash is replaced with \\

Tong Sun

unread,
Aug 14, 2017, 10:48:14 AM8/14/17
to golang-nuts
I've wrapped into a tool, and here is why I'm doing that... 


Usage


jsonfiddle esc will escape any arbitrary string so as to embed it as content of json string. This seems useless at first, but it actually allows you to embed any arbitrary file into GitHub Gists JSON API, so as to post any arbitrary file onto GitHub Gist:


echo '{"description":"SmartyStreets API Demo","public":true,"files":{"SmartyStreets.json":{"content":'"`jsonfiddle fmt -i test/SmartyStreets.json | jsonfiddle esc -i`"'}}}' | curl --data @- https://api.github.com/gists


This will give you https://gist.github.com/anonymous/1423d4768dd9b88262ca513626e68d8e


By "arbitrary file" I do mean arbitrary file. Check this out:

https://gist.github.com/anonymous/a51798ce99ff59d8d4ba536cbf4b6996


This is why jsonfiddle esc is a command on its own, instead of being part of functionalities of jsonfiddle fmt or jsonfiddle sort.

Reply all
Reply to author
Forward
0 new messages