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条)

报告相同问题?