登录
首页 >  Golang >  Go问答

缩进包含 JSON 之类数据的字符串

来源:stackoverflow

时间:2024-04-15 12:30:28 440浏览 收藏

最近发现不少小伙伴都对Golang很感兴趣,所以今天继续给大家介绍Golang相关的知识,本文《缩进包含 JSON 之类数据的字符串》主要内容涉及到等等知识点,希望能帮到你!当然如果阅读本文时存在不同想法,可以在评论中表达,但是请勿使用过激的措辞~

问题内容

我有一个如下所示的字符串:

"{out: \"world\", out2: \"hello\", employee: {name: \"singh\", emailid: \"[email protected] [email protected]\", address: {street_name: \"xxxxxx\", old_address: {old_street_name: \"xxxxxx\"}}, emp_code: \"12345678\"}, array2: [\"first\", \"second\"]}"

我想得到如下输出。我确实尝试在这里使用 json.marshalindent() https://play.golang.org/p/ujbkns00__k 但它返回相同的字符串而不缩进。

{
  "out": "world",
  "out2": "hello",
  "employee":
     {
      "name": "Singh",
      "emailid": "[email protected] [email protected]",
      "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
}

接下来,您可以使用 gjson 库解析 json 字符串并使用 gjson 结果。或者您可以使用标准 golang json 库中的 json.unmarshal(obj) 。

理论要掌握,实操不能落!以上关于《缩进包含 JSON 之类数据的字符串》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>