在Go中为JSON指定分隔符

时间:2014-06-05 09:10:03

标签: json go

我想在Go中使用JSON的自定义分隔符,相当于Python的:

json.dumps([1,2,3,{'4': 5, '6': 7}], separators=(',',':'))

如何在Go中为JSON指定分隔符?

澄清

json.dumps({"key1":"value1","key2":"value2"}, separators=('__','..'))

'{"key2".."value2"__"key1".."value1"}'

此要求有一些有效的用例:

http://mens.com?&cyclone_data={"VisitorId":"53905341bd05ae26a9000001","CampaignId":"538f278cbd05ae36c6000001","LandingPageId":"538eac3ebd05ae15fe000001","OfferId":"538f097ebd05ae2a4d000001","SourceId":"538f0e39bd05ae2b9c000002","NetworkId":""}

我需要在cookie中设置相同的URL:

tracking_data=http://mens.com?&cyclone_data={"VisitorId":"53905341bd05ae26a9000001","CampaignId":"538f278cbd05ae36c6000001","LandingPageId":"538eac3ebd05ae15fe000001","OfferId":"538f097ebd05ae2a4d000001","SourceId":"538f0e39bd05ae2b9c000002","NetworkId":""}

使用http.SetCookie()设置Cookie后,Chrome Web Developer工具会显示:

Date:Thu, 05 Jun 2014 11:23:46 GMT
Location:http://mens.com?&cyclone_data={"VisitorId":"53905341bd05ae26a9000001","CampaignId":"538f278cbd05ae36c6000001","LandingPageId":"538eac3ebd05ae15fe000001","OfferId":"538f097ebd05ae2a4d000001","SourceId":"538f0e39bd05ae2b9c000002","NetworkId":""}
Set-Cookie:538f278cbd05ae36c6000001=538f278cbd05ae36c6000001; Path=/
Set-Cookie:cyclone-track-url=http://mens.com?&cyclone_data={VisitorId:53905341bd05ae26a9000001CampaignId:538f278cbd05ae36c6000001LandingPageId:538eac3ebd05ae15fe000001OfferId:538f097ebd05ae2a4d000001SourceId:538f0e39bd05ae2b9c000002NetworkId:} Content-Length:378
Content-Type:text/html; charset=utf-8

,""缺失。

我知道base64。我希望用户能够在没有任何手动编码/解码程序的情况下更改VisitorId

服务器端应用程序从Cookie和Browser Referer中读取并比较此URL。

发现此问题: https://code.google.com/p/go/issues/detail?id=7243

1 个答案:

答案 0 :(得分:2)

嗯,你不能直接,但如果我想要删除多余的不需要的空格,你可以使用json.Compact

http://golang.org/pkg/encoding/json/#Compact

它只需要你的编码json并删除不必要的空格。

您还可以尝试使用json.MarshalIndent方法进行游戏,以便控制缩进分隔符。但是AFAIK,你不能指定非标准的分隔符。