将JSON字符串中的JS数组解析为Golang映射

时间:2016-07-21 06:14:22

标签: arrays json go

API I查询返回一个JSON,其中一个元素应该是一个数组,但是用引号括起来。因此,似乎“encoding / json”包不能将该元素识别为数组。

当我尝试将该元素作为地图访问时,我收到错误:

interface conversion: interface is string, not []interface {}

游乐场:https://play.golang.org/p/K1H01q-Dqc

package main

import (
    "fmt"
    "encoding/json"
)

func check(e error) {
    if e != nil {
        panic(e)
    }
}

var incomingJson string = `{
    "status":"success",
    "content":"[{\"id\":\"567670128\"},{\"id\":\"567670129\"}]"
    }`

func main() {

    // Decode incoming json
    var encodedJson map[string]interface{}
    err := json.Unmarshal([]byte(incomingJson), &encodedJson)
    check(err)
    fmt.Println(encodedJson)

    // Accessing "content" data
    contentOjects := encodedJson["content"].([]interface{})
    contentObject0 := contentOjects[0].(map[string]string)
    fmt.Println(contentObject0)
} 

我应该如何转换/转换["content"]中的字符串,以便将其解析为map[string]string

1 个答案:

答案 0 :(得分:3)

"content"的值是一个JSON字符串,顺便说一句是另一个JSON编码的文本。因此,如果这是您得到的,您可以解组"content"的值,就像您解组任何其他JSON文本一样:

var contentOjects []interface{}
err = json.Unmarshal([]byte(encodedJson["content"].(string)), &contentOjects)
check(err)
contentObject0 := contentOjects[0].(map[string]interface{})
fmt.Println(contentObject0)

输出:

map[id:567670128]

或者,如果您知道[]map[string]interface{}只包含[]map[string]string个值,则可以将其解组为string类型的值(如果知道它只包含// Accessing "content" data var contentOjects2 []map[string]interface{} err = json.Unmarshal([]byte(encodedJson["content"].(string)), &contentOjects2) check(err) fmt.Println(contentOjects2[0]) ),则可以将其解组为:

map[id:567670128]

输出相同:

window.onload = function(){

        var room = "2";


        // Create webrtc connection
        var webrtc = new SimpleWebRTC({
            localVideoEl: 'publisher',
            remoteVideosEl: '',
            autoRequestMedia: true,
            log: true,
            debug: false,
            detectSpeakingEvents: true,
            autoAdjustMic: false
        });


        // we did not get access to the camera
        webrtc.on('localMediaError', function (err) {
        });


        // a peer video has been added
        webrtc.on('videoAdded', function (video, peer) {
            console.log('video added', peer);

            var remotes = document.getElementById('subscriber');

            if (remotes) {
                var container = document.createElement('div');
                container.className = 'videoContainer';
                container.setAttribute('data-user', userType);
                // $div.attr('data-user', streamUser.userType);
                container.setAttribute('class', 'col-md-6 each-video'); 
                container.id = 'container_' + webrtc.getDomId(peer);
                container.appendChild(video);

                remotes.appendChild(container);


            }
        });

        // a peer video has been removed

        // a peer video was removed
        webrtc.on('videoRemoved', function (video, peer) {
            console.log('video removed ', peer);
            var remotes = document.getElementById('subscriber');
            var el = document.getElementById(peer ? 'container_' + webrtc.getDomId(peer) : 'localScreenContainer');
            if (remotes && el) {
                remotes.removeChild(el);
            }
        });



        // when it's ready and we have a room from url, join the call
        webrtc.on('readyToCall', function(){
            if(room) webrtc.joinRoom(room);
        });


        if(room){
            webrtc.createRoom(room, function(err, name){
                    if(err){
                        console.log(err);
                    }
                });
        }



         }

Go Playground上尝试这些。