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 请问为什么我配置IPsec后PC1 ping不通 PC2,抓包出来数据包也并没有被加密
  • ¥200 求博主教我搞定neo4j简易问答系统,有偿
  • ¥15 nginx的使用与作用
  • ¥100 关于#VijeoCitect#的问题,如何解决?(标签-ar|关键词-数据类型)
  • ¥15 一个矿井排水监控系统的plc梯形图,求各程序段都是什么意思
  • ¥50 安卓10如何在没有root权限的情况下设置开机自动启动指定app?
  • ¥15 ats2837 spi2从机的代码
  • ¥200 wsl2 vllm qwen1.5部署问题
  • ¥100 有偿求数字经济对经贸的影响机制的一个数学模型,弄不出来已经快要碎掉了
  • ¥15 数学建模数学建模需要