thedevsaddam / gojsonq

A simple Go package to Query over JSON/YAML/XML/CSV Data
https://github.com/thedevsaddam/gojsonq/wiki
MIT License
2.18k stars 140 forks source link

How to get the queried data to user defined custom type? #29

Closed thedevsaddam closed 5 years ago

thedevsaddam commented 5 years ago

How can I get the output data to a custom struct like:

Input document:

{
  "items":[
    {
      "id":1,
      "name":"MacBook Pro 13 inch retina",
      "price":1350
    },
    {
      "id":2,
      "name":"MacBook Pro 15 inch retina",
      "price":1700
    }
  ]
}

Code:

type item struct {
    ID    int    `json:"id"`
    Name  string `json:"name"`
    Price int    `json:"price"`
}

func main() {
    v := item{}
    output := gojsonq.New().File("./data.json").From("items.[0]").Get()
        // how to assign the output value to v
}

What I want:

package main

import (
    "github.com/davecgh/go-spew/spew"
    "github.com/thedevsaddam/gojsonq"
)

type item struct {
    ID    int     `json:"id"`
    Name  string  `json:"name"`
    Price float64 `json:"price"`
}

func main() {
    v := item{}
    jq := gojsonq.New().File("./data.json").From("items.[0]")
    jq.Out(&v)
    if jq.Error() != nil {
        panic(jq.Error())
    }
    spew.Dump(v)
}

// Output:
// (main.item) {
//  ID: (int) 1,
//  Name: (string) (len=26) "MacBook Pro 13 inch retina",
//  Price: (float64) 1350
// }
thedevsaddam commented 5 years ago

Available from Version: v1.9.0