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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?