dounouxi1020 2014-08-30 14:14
浏览 62
已采纳

在不使用结构的情况下将JSON转换为地图切片并将地图切片转换为Go

I am trying to convert a json string from an http request to a slice of map/s. And I should also convert a slice of map/s to json string to use for a http response.

I want to convert the followings into a slice of map/s, in both cases below. The json string from the http request may be an array of several same key value json objects, like;

[
        { title: 'JavaScript: The Good Parts', author: 'Douglas Crockford',
          releaseDate: '2008', keywords: 'JavaScript Programming' },
        { title: 'The Little Book on CoffeeScript', author: 'Alex MacCaw',
          releaseDate: '2012', keywords: 'CoffeeScript Programming' },
        { title: 'Scala for the Impatient', author: 'Cay S. Horstmann',
          releaseDate: '2012', keywords: 'Scala Programming' },
        { title: 'American Psycho', author: 'Bret Easton Ellis',
          releaseDate: '1991', keywords: 'Novel Splatter' },
        { title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
          releaseDate: '2011', keywords: 'JavaScript Programming' }
]

or a single one like;

{ title: 'Eloquent JavaScript', author: 'Marijn Haverbeke',
  releaseDate: '2011', keywords: 'JavaScript Programming' }

And the second task is to convert a slice of map/s to a json string.

However, I could not mange to succeed in these two procedures.

json package makes it possible to do these two tasks for structs, I am aware of it.

I should not use structs coded beforehand, for a design concern.

Is there a known way to do these in Go.

  • 写回答

2条回答 默认 最新

  • dongshi1606 2014-08-30 18:00
    关注

    You really can use use map[string]interface{} and that would work with { "title": ....., "keywords": ["CoffeeScript", "Programming"] } just fine

    You'd have to use something like :

    for i := 0; i < len(b); i++ {
        fmt.Printf("%s by %s was release at %s
    ", b[i]["title"], b[i]["author"])
        switch v := b[i]["keywords"].(type) {
        case []interface{}:
            for i := 0; i < len(v); i++ {
                switch v := v[i].(type) {
                case string:
                    fmt.Println("\tstring in a slice", v)
                case float64: //numbers in json are float64 by default
                    fmt.Println("\tnumber in a slice", v)
                default:
                    fmt.Printf("\tunknown type (%T)", v, v)
                }
            }
        case string:
            fmt.Println("\tstring", v)
        }
    }
    

    <kbd>playground</kbd>

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于#flink#的问题:关于docker部署flink集成hadoop的yarn,请教个问题flink启动yarn-session.sh连不上hadoop
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 lammps拉伸应力应变曲线分析
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题