本文介绍了golang有一种解组任意复杂json的简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网上看到的每个示例都展示了以下示例:为数据构建结构,然后将JSON编组为数据类型.问题是我得到的是大量的JSON转储,使用这种方法似乎很费力.

是否有一种方法可以处理大量数据,并将其解组为类似于json/maps的对象之类的地图?

我现在所拥有的就是这样...

  var数据映射[interface {}]接口{}err = json.Unmarshal(JSONDUMP,& data)如果err!= nil {log.Fatal(err)} 

但是我不能这样称呼

  data ["some"] ["long"] ["chain"] ["of"] ["lookups"](类型接口{}不支持索引) 
解决方案

通常,这是一个不好的主意!但是,如果您确实需要,可以执行以下操作:

 程序包主要进口 (编码/json""fmt")func main(){var anyJson map [string] interface {}customJSON:= [] byte(`{"a":文字来了","b":{"c":10,"d":更多文字"}}`)json.Unmarshal(customJSON,& anyJson)fmt.Println("a ==",anyJson ["a"].(字符串))b_temp:= anyJson ["b"].(map [string]接口{})fmt.Println("c ==",b_temp ["c"].(float64))} 

..那么您可以使用 anyJson ["a"].(string)之类的任何字段-查看类型断言,有效是至关重要的

Every example I come to online shows examples of building structs for the data and then unmarshaling JSON into the data type. The problem is that what I am getting is massive dump of JSON and it seems like backbreaking labor to use such a method....

Is there a way to take a huge dump of data and get it to unmarshal into a map like object that would function similar to json/maps?

What I have right now is like this...

var data map[interface{}]interface{}
err = json.Unmarshal(JSONDUMP, &data)
if err != nil { log.Fatal(err) }

but then I cannot call it like this

data["some"]["long"]["chain"]["of"]["lookups"]
(type interface {} does not support indexing)
解决方案

In general this is a bad idea! But if you really need, you can do like this:

package main

import (
    "encoding/json"
    "fmt"
)

func main() {
    var anyJson map[string]interface{}

    customJSON := []byte(`{"a": "text comes here", "b": {"c":10, "d": "more text"}}`)

    json.Unmarshal(customJSON, &anyJson)

    fmt.Println("a ==", anyJson["a"].(string))

    b_temp := anyJson["b"].(map[string]interface{})
    fmt.Println("c ==", b_temp["c"].(float64))
}

.. then you can use any field like anyJson["a"].(string) - look at type assertion, it's critically important to be valid

这篇关于golang有一种解组任意复杂json的简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-06 18:17