解析失败,无效字符'{‘在顶层值之后。

huangapple go评论91阅读模式
英文:

Failed Unmarshal for xxx invalid character '{' after top-level value

问题

失败的反序列化,因为顶级值后面有无效字符'{'。

package main
import (...)

type hostInfo struct {
    Name string
}

var b bytes.Buffer
var c bytes.Buffer
var tmphostInfo hostInfo
var result map[string]interface{}

func main() {
    keypath := os.Args[1]
    hostiplist := []string {"192.168.1.150","192.168.1.151","192.168.1.152","192.168.1.153"}
    port := "22"
    key,err := ioutil.ReadFile(keypath)
    if err != nil {
        log.Fatalf("无法读取私钥:%v", err)
    }
    signer,err:=ssh.ParsePrivateKey(key)
    if err != nil {
        log.Fatalf("无法解析私钥:%v",err)
    }
    var conn *ssh.Client

    config := &ssh.ClientConfig{
        User:            "support",
        Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
        HostKeyCallback: ssh.InsecureIgnoreHostKey(),
        Timeout: 5*time.Second,
    }
    for _,hostip := range hostiplist {
        conn,err = ssh.Dial("tcp",net.JoinHostPort(hostip,port),config)
        if err != nil {
            log.Fatalf("无法连接:%v",err)
        }
        defer conn.Close()
        session1,err:=conn.NewSession()
        if err != nil {
            log.Fatalf("无法连接:%v",err)
        }
        defer session1.Close()
        session1.Stdout = &b
        if err := session1.Run("some mongo query"); err != nil {
            log.Fatal("运行失败:sess1 " + err.Error())
        }
        tmphostInfo=hostInfo{}
        fmt.Printf("tmphostInfo: %v , ip : %s",tmphostInfo.Name,hostip)
        err1 := json.Unmarshal([]byte(""),&tmphostInfo)
        if err1 != nil {
            log.Fatalf("无法反序列化 LP 名称 %v,IP:%s",err1,hostip)
        }

        session2,err:=conn.NewSession()
        session2.Stdout = &c
        if err := session2.Run("another mongo query"); err != nil {
            log.Fatal("运行失败:sess2 " + err.Error())
        }

        err2 := json.Unmarshal([]byte(c.String()),&result)
        if err2 != nil {
            log.Fatalf("无法反序列化客户名称 %v",err2)
        }
        //fmt.Println(c.String())
        custmap := result["customer"].(map[string]interface{})
        //fmt.Println(birds)
        var LPname string
        for key, value := range custmap {
            // Each value is an interface{} type, that is type asserted as a string
            //fmt.Println(key, value.(string))
            if key == "name" {
                LPname=value.(string)
            }
        }
        fmt.Println(hostip,tmphostInfo.Name,LPname)
        f, err := os.OpenFile("/tmp/supportip.csv", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
        if err != nil {
            log.Fatal(err)
        }
        if _, err := f.Write([]byte(hostip+","+tmphostInfo.Name+","+LPname+"\n")); err != nil {
            log.Fatal(err)
        }
        if err := f.Close(); err != nil {
            log.Fatal(err)
        }
    }

}

go run scan.go /path/to/key 的结果是

tmphostInfo: {} , ip : 192.168.1.150 10.45.9.141 servername1 DFIDorg
tmphostInfo: {} , ip : 192.168.1.151 2021/12/10 15:07:36 **无法反序列化 LP 名称无效字符 '{'**IP192.168.1.151
exit status 1


第一个数组元素192.168.1.150的两个查询结果都成功反序列化但是第二个和后面的项目失败了

第一个查询的 JSON 字符串如下所示

{ "name" : "john doe" }

第二个查询的结果如下所示

{
        "customer" : {
                "address1" : "ktm",
                "secret_key" : "12237918f0d441d25fb",
                "address2" : "",
                "name" : "KUKL Limited",
                "phone" : "12345"
        }
}
英文:

Failed Unmarshal for LP name invalid character '{' after top-level value

package main
import (...)
type hostInfo struct {
Name string
}
var b bytes.Buffer
var c bytes.Buffer
var tmphostInfo hostInfo
var result map[string]interface{}
func main() {
keypath := os.Args[1]
hostiplist := []string {"192.168.1.150","192.168.1.151","192.168.1.152","192.168.1.153"}
port := "22"
key,err := ioutil.ReadFile(keypath)
if err != nil {
log.Fatalf("Unable to read private key: %v", err)
}
signer,err:=ssh.ParsePrivateKey(key)
if err != nil {
log.Fatalf("Unable to parse private key: %v",err)
}
var conn *ssh.Client
config := &ssh.ClientConfig{
User:            "support",
Auth:            []ssh.AuthMethod{ssh.PublicKeys(signer)},
HostKeyCallback: ssh.InsecureIgnoreHostKey(),
Timeout: 5*time.Second,
}
for _,hostip := range hostiplist {
conn,err = ssh.Dial("tcp",net.JoinHostPort(hostip,port),config)
if err != nil {
log.Fatalf("unable to connect: %v",err)
}
defer conn.Close()
session1,err:=conn.NewSession()
if err != nil {
log.Fatalf("unable to connect: %v",err)
}
defer session1.Close()
session1.Stdout = &b
if err := session1.Run("some mongo query"); err != nil {
log.Fatal("Failed to run:sess1 " + err.Error())
}
tmphostInfo=hostInfo{}
fmt.Printf("tmphostInfo: %v , ip : %s",tmphostInfo.Name,hostip)
err1 := json.Unmarshal([]byte(""),&tmphostInfo)
if err1 != nil {
log.Fatalf("Failed Unmarshal for LP name %v for IP %s",err1,hostip)
}
session2,err:=conn.NewSession()
session2.Stdout = &c
if err := session2.Run("another mongo query"); err != nil {
log.Fatal("Failed to run:sess2 " + err.Error())
}
err2 := json.Unmarshal([]byte(c.String()),&result)
if err2 != nil {
log.Fatalf("Failed Unmarshal for Customer name %v",err2)
}
//fmt.Println(c.String())
custmap := result["customer"].(map[string]interface{})
//fmt.Println(birds)
var LPname string
for key, value := range custmap {
// Each value is an interface{} type, that is type asserted as a string
//fmt.Println(key, value.(string))
if key == "name" {
LPname=value.(string)
}
}
fmt.Println(hostip,tmphostInfo.Name,LPname)
f, err := os.OpenFile("/tmp/supportip.csv", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
log.Fatal(err)
}
if _, err := f.Write([]byte(hostip+","+tmphostInfo.Name+","+LPname+"\n")); err != nil {
log.Fatal(err)
}
if err := f.Close(); err != nil {
log.Fatal(err)
}
}
}

go run scan.go /path/to/key results in

tmphostInfo: {} , ip : 192.168.1.150 10.45.9.141 servername1 DFIDorg
tmphostInfo: {} , ip : 192.168.1.151 2021/12/10 15:07:36 Failed Unmarshal for LP name invalid character '{' after top-level value for 192.168.1.151
exit status 1

The unmarshal for both queries result for first array element "192.168.1.150" is successful but fails on second and rest of items

The json string for first query looks like below

{ "name" : "john doe" } 

result of second query looks like

{
"customer" : {
"address1" : "ktm",
"secret_key" : "12237918f0d441d25fb",
"address2" : "",
"name" : "KUKL Limited",
"phone" : "12345"
}
}

答案1

得分: 2

在for循环开始后,我不得不重置bytes.Buffer变量。问题是从ssh执行中获取的结果已经被追加到了buffer中,而这个buffer无法被反序列化。

for _, hostip := range hostiplist {
    b.Reset()
    c.Reset()
    // 其他代码...
}
英文:

I had to reset the bytes.Buffer variable right after the for loop start, the issue was that the result pulled from ssh execution had been appended to buffer which could not be deserialized

 for _,hostip := range hostiplist {
b.Reset()
c.Reset()

huangapple
  • 本文由 发表于 2021年12月10日 17:34:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/70302406.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定