Modify behavior of Array() on non-array result.

Closes #10.
This commit is contained in:
William Poussier 2016-11-02 20:20:24 +01:00
parent b95abbe94a
commit 495633298f
2 changed files with 24 additions and 11 deletions

View File

@ -138,16 +138,17 @@ func (t Result) Float() float64 {
}
}
// Array returns back an array of children. The result must be a JSON array.
// Array returns back an array of children. If the result is not
// a JSON array, the return will be an array containing one result.
func (t Result) Array() []Result {
if t.Type != JSON {
return nil
return []Result{t}
}
r := t.arrayOrMap('[', false)
return r.a
}
// Map returns back an map of children. The result should be a JSON array.
// Map returns back an map of children. The result should be a JSON array.
func (t Result) Map() map[string]Result {
if t.Type != JSON {
return map[string]Result{}

View File

@ -105,18 +105,18 @@ var basicJSON = `{"age":100, "name":{"here":"B\\\"R"},
"loggy":{
"programmers": [
{
"firstName": "Brett",
"lastName": "McLaughlin",
"firstName": "Brett",
"lastName": "McLaughlin",
"email": "aaaa"
},
},
{
"firstName": "Jason",
"lastName": "Hunter",
"firstName": "Jason",
"lastName": "Hunter",
"email": "bbbb"
},
},
{
"firstName": "Elliotte",
"lastName": "Harold",
"firstName": "Elliotte",
"lastName": "Harold",
"email": "cccc"
},
{
@ -445,6 +445,18 @@ func TestUnmarshalMap(t *testing.T) {
}
}
func TestSingleArrayValue(t *testing.T) {
var json = `{"key": "value"}`
var result = Get(json, "key")
var array = result.Array()
if len(array) != 1 {
t.Fatal("array is empty")
}
if array[0].String() != "value" {
t.Fatal("got %s, should be %s", array[0].String(), "value")
}
}
type BenchStruct struct {
Widget struct {
Window struct {