doujiongqin0687 2017-11-01 00:26
浏览 65
已采纳

从JSON字符串值解析JSON

I want to convert from string to object.

From

{"key1": "{
  \"key2\": \"value2\",
  \"key3\": {
    \"key4\": \"value4\"
  }
}
"}

To

{"key1": {"key2": "value2", "key3": {"key4": "value4"}}}

Finally, I want to get value4.

I can get the value of "key1" using below script.

jsondata := `{"key1": "{
  \"key2\": \"value2\",
  \"key3\": {
    \"key4\": \"value4\"
  }
}
"}`
var m map[string]interface{}
json.Unmarshal([]byte(jsondata), &m)
value := m["key1"]
fmt.Println(value)

https://play.golang.org/p/4lwgQJfp5S

But I can't convert the value to an object. So I can't get "value4". Are there methods for this? I can get it by regex like https://play.golang.org/p/6TB-qNAdgQ But now this is not my solution.

Thank you so much for your time and advices. And I'm sorry for my immature question.

  • 写回答

1条回答 默认 最新

  • duandan1995 2017-11-01 01:09
    关注

    There are two levels of JSON encoding. The first step is to decode the outer JSON value. Decode to a struct matching the structure of the JSON.

    var outer struct{ Key1 string }
    if err := json.Unmarshal([]byte(jsondata), &outer); err != nil {
        log.Fatal(err)
    }
    

    The next step is to decode the inner JSON value. Again, decode to a struct matching the structure of the JSON.

    var inner struct{ Key3 struct{ Key4 string } }
    if err := json.Unmarshal([]byte(outer.Key1), &inner); err != nil {
        log.Fatal(err)
    }
    // The value is inner.Key3.Key4
    

    playground example

    If the JSON is not double encoded, you can decode in one shot:

    jsondata := `{"key1": { "key2": "value2",  "key3": { "key4": "value4"  }}}`
    var v struct {
        Key1 struct{ Key3 struct{ Key4 string } }
    }
    if err := json.Unmarshal([]byte(jsondata), &v); err != nil {
        log.Fatal(err)
    }
    // value is v.Key1.Key3.Key4
    

    playground example

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题