Go 缩进包含类似JSON数据的字符串
我有一个字符串,如下所示:Go 缩进包含类似JSON数据的字符串,go,Go,我有一个字符串,如下所示: "{out: \"world\", out2: \"hello\", employee: {name: \"Singh\", emailid: \"simran@yahoo.com gur@yahoo.com\", address: {street_name: \"xxxxxx\", old_address: {old_street_name: \"xxxxxx\"}}, emp_code: \"12345678\"}, array2: [\"first\",
"{out: \"world\", out2: \"hello\", employee: {name: \"Singh\", emailid: \"simran@yahoo.com gur@yahoo.com\", address: {street_name: \"xxxxxx\", old_address: {old_street_name: \"xxxxxx\"}}, emp_code: \"12345678\"}, array2: [\"first\", \"second\"]}"
我想得到如下输出。我确实尝试在这里使用Json.MarshalIndent(),但它返回相同的字符串,而不缩进
{
"out": "world",
"out2": "hello",
"employee":
{
"name": "Singh",
"emailid": "simran@yahoo.com gur@yahoo.com",
"address":
{
"street_name": "xxxxxx",
"old_address":
{
"old_street_name": "xxxxxx"
}
},
"emp_code": "12345678"
},
"array2": ["first","second"]
}
我认为您可以使用下面的函数,只需稍加修改就可以从类似JSON的字符串中删除“\”,然后将其解组
func StripSlashes(s string) string {
s = strings.Replace(s, "\", "", -1)
return s
}
接下来,您可以使用parson JSON字符串库并使用gjson结果。或者可以使用stand Golang JSON库中的JSON.unmarshal(obj) 该字符串是一个带引号的JSON字符串。如果要缩进内容,需要先将其解压缩/解组。示例字符串开头不是有效的json,并且示例中包含嵌套字符串中的json——您正在尝试处理哪一个?如果您有有效的任意json,只需在执行strconv.Unquote(st)时使用@Flimzy即可,我将返回空字符串。您可以在中使用相同的输入字符串粘贴示例。提前谢谢。@JimB对不起,我没听清楚。为什么字符串不是有效的json,因为有“\”个字符?如果我们有下面这样的字符串呢<代码>{员工:{emp_代码:“12345678”,姓名:“Gursimran Singh”,电子邮件ID:simran@yahoo.com gur@yahoo.com,地址:{街道名称:“xx xx xx”,旧街道地址:{旧街道名称:“xx xxx”}},排列2:[“第一”,“第二”],输出:“世界”,输出2:“你好”}您能建议如何转换上述输入字符串吗?@Gursimran:json不允许使用无引号的键,并且您有无引号的键<如果您从json开始,代码>缩进可以正常工作:gjson正在弄乱输入。它正在删除键并创建新的键值对。