Jeffail/gabs

Gabs will not parse an array at the top level

Closed this issue · 4 comments

From (http://www.json.org):

JSON is built on two structures:

A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.

When passing an array into gabs:

import (
    "github.com/jeffail/gabs"
    "fmt"
)

json, err := gabs.ParseJSON([]byte(`[]`))
fmt.Printf("%+v", err)

The input text could not be parsed error is generated. It seems to be because of this line in func ParseJSON:

if _, ok := gabs.object.(map[string]interface{}); ok {

Whether or not that if statement is the only thing preventing parsing arrays, I'm not sure of but I think this is something that definitely needs resolving.

I took a more in-depth look at the code. It seems that it is definitely possible to have a top-level array with a bit of work. For now until I am able to make a pull request, or someone else fixes this, here's an ugly hack that works around the issue for now:

package main

import (
    "github.com/jeffail/gabs"
    "fmt"
    "encoding/json"
)

func main () {
    var object interface{}
    jsonObject := gabs.New()
    _ = json.Unmarshal([]byte(`[{"name":"a"},{"name":"b"}]`), &object)
    jsonObject.SetP(object, "array")
    children, _ := jsonObject.S("array").Children()
    for _, v := range children {
        fmt.Print(v.StringIndent("", "    "))
    }
}
/**
 * Prints
 * {
 *     "name" : "a"
 * } {
 *     "name" : "b"
 * }
 */

Hey @jaitaiwan, if memory serves me this was simply because at one time gabs was unable to work with arrays, so an array at the root would be unusable in gabs. This isn't the case any more so you're right that this needs fixing. I can quickly add this in (probably tomorrow).

Hey @jaitaiwan,

b69c9e6 should fix this, gabs now allows any valid JSON value at the root, and you can manipulate the root value itself.

Thanks!

On Thu, 5 Nov 2015 5:49 am Ashley Jeffs notifications@github.com wrote:

Hey @jaitaiwan https://github.com/jaitaiwan,

b69c9e6
b69c9e6
should fix this, gabs now allows any valid JSON value at the root, and you
can manipulate the root value itself.


Reply to this email directly or view it on GitHub
#10 (comment).