Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to use JSON parser #123

Open
devoid opened this issue May 31, 2016 · 1 comment
Open

How to use JSON parser #123

devoid opened this issue May 31, 2016 · 1 comment
Labels
v1 Relates to the v1 line of releases

Comments

@devoid
Copy link

devoid commented May 31, 2016

I am having trouble understanding how the json packages should be used. I can't seem to get a valid AST out of a struct. The following prints invalid HCL (at least I think) and then panics during the Decode step.

package main

import (
    "bytes"
    "fmt"

    "github.com/hashicorp/hcl"
    "github.com/hashicorp/hcl/hcl/printer"
    "github.com/hashicorp/hcl/json/parser"
)

type Body struct {
    Fruits []Fruit `json:"fruits" hcl:"fruits"`
}

type Fruit struct {
    Name string `json:"name"`
}

func main() {
    text := `
{
    "fruits" : [
        { "name" : "apple" },
        { "name" : "orange" },
        { "name" : "pear" }
    ]
}`
    ast, err := parser.Parse([]byte(text))
    if err != nil {
        panic(err)
    }

    buff := bytes.NewBuffer(nil)
    printer.Fprint(buff, ast)
    fmt.Println("HCL:")
    fmt.Printf("%s\n", buff.String())

    b := &Body{}
    err = hcl.Decode(&b, buff.String())
    if err != nil {
        panic(err)
    }
}
@promiseofcake
Copy link

I have the same question. 🤔

@apparentlymart apparentlymart added the v1 Relates to the v1 line of releases label Aug 27, 2018
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
v1 Relates to the v1 line of releases
Projects
None yet
Development

No branches or pull requests

3 participants