Golang中没有Struct的动态JSON解析器

追梦人在路上不断追寻 · · 592 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

Gabs是一个小型实用程序,用于处理Go中的动态或未知JSON结构。它不需要您知道有效负载的结构(例如,创建结构),并且可以通过提供指向它们的路径来访问字段。它几乎只是一个有用的包装,用于导航由encoding / json包提供的map [string] interface {}对象的层次结构。除了出色之外,它没有任何壮观的东西。

安装

go get github.com/Jeffail/gabs

例子

package main

import (
    "fmt"

    "github.com/Jeffail/gabs"
)

func main() {
    data := []byte(`{
        "employees":{
           "protected":false,
           "address":{
              "street":"22 Saint-Lazare",
              "postalCode":"75003",
              "city":"Paris",
              "countryCode":"FRA",
              "country":"France"
           },
           "employee":[
              {
                 "id":1,
                 "first_name":"Jeanette",
                 "last_name":"Penddreth"
              },
              {
                 "id":2,
                 "firstName":"Giavani",
                 "lastName":"Frediani"
              }
           ]
        }
     }`)

    jsonParsed, err := gabs.ParseJSON(data)
    if err != nil {
        panic(err)
    }

    // Search JSON
    fmt.Println("Get value of Protected:\t", jsonParsed.Path("employees.protected").Data())
    fmt.Println("Get value of Country:\t", jsonParsed.Search("employees", "address", "country").Data())
    fmt.Println("ID of first employee:\t", jsonParsed.Path("employees.employee.0.id").String())
    fmt.Println("Check Country Exists:\t", jsonParsed.Exists("employees", "address", "countryCode"))

    // Iterating address objects
    for key, child := range jsonParsed.Search("employees", "address").ChildrenMap() {
        fmt.Printf("Key=>%v, Value=>%v\n", key, child.Data().(string))
    }

    // Iterating employee array
    for _, child := range jsonParsed.Search("employees", "employee").Children() {
        fmt.Println(child.Data())
    }

    // Use index in your search
    for _, child := range jsonParsed.Search("employees", "employee", "0").Children() {
        fmt.Println(child.Data())
    }
}

下面的输出。

Get value of Protected:  false
Get value of Country:    France
ID of first employee:    1
Check Country Exists:    true
Key=>street, Value=>22 Saint-Lazare
Key=>postalCode, Value=>75003
Key=>city, Value=>Paris
Key=>countryCode, Value=>FRA
Key=>country, Value=>France
map[id:1 first_name:Jeanette last_name:Penddreth]
map[id:2 firstName:Giavani lastName:Frediani]
Jeanette
Penddreth
1

有疑问加站长微信联系(非本文作者)

本文来自:简书

感谢作者:追梦人在路上不断追寻

查看原文:Golang中没有Struct的动态JSON解析器

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

592 次点击  
加入收藏 微博
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传