简体   繁体   English

如何解组json数组?

[英]How to Unmarshal the json array?

There is something wrong when I unmarshal the json array. 当我解组json数组时出了点问题。
How do I correct it ? 我该如何纠正? the code is: http://play.golang.org/p/AtU9q8Hlye 该代码是: http : //play.golang.org/p/AtU9q8Hlye

package main

import (
    "encoding/json"
    "fmt"
)

type Server struct {
    ServerName string
    ServerIP   string
}

type Serverslice struct {
    Name    string
    Servers []Server
}

func main() {
    var s []Serverslice
    str := `{"name":"dxh","servers":[{"serverName":"VPN0","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}],
        "name":"dxh1,"servers":[{"serverName":"VPN1","serverIP":"127.0.0.1"},{"serverName":"Beijing_VPN","serverIP":"127.0.0.2"}]}`

    json.Unmarshal([]byte(str), &s) //the wrong line.....................
    fmt.Println(len(s))
}

First of all, you're ignoring the error return value from json.Unmarshal . 首先,您将忽略json.Unmarshal的错误返回值。 You probably want something like: 您可能想要类似:

if err := json.Unmarshal([]byte(str), &s); err != nil {
    log.Fatalln(err)
}

With that change, we can see that your JSON data isn't valid: invalid character 's' after object key:value pair . 进行此更改后,我们可以看到您的JSON数据无效: invalid character 's' after object key:value pair There is a missing quote at the end of "dxh1 on the second line. 在第二行"dxh1的末尾缺少引号。

Fixing that error and rerunning the program you'll get a different error: json: cannot unmarshal object into Go value of type []main.Serverslice . 修复该错误并重新运行程序,您将收到另一个错误: json: cannot unmarshal object into Go value of type []main.Serverslice There are two possible problems here: 这里有两个可能的问题:

  1. You meant to decode into an object. 您打算解码成一个对象。 In this case, just declare s as a Serverslice . 在这种情况下,只需将s声明为Serverslice Here is a version of your program that makes that change: http://play.golang.org/p/zgyr_vnn-_ 这是可以进行更改的程序版本: http : //play.golang.org/p/zgyr_vnn-_

  2. Your JSON is supposed to be an array (possible, since it seems to have duplicate keys). 您的JSON应该是一个数组(可能,因为它似乎有重复的键)。 Here's an updated version with the JSON changed to provide an array: http://play.golang.org/p/Wl6kUaivEm 这是JSON更改为提供数组的更新版本: http : //play.golang.org/p/Wl6kUaivEm

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM