diff --git a/api_test.go b/api_test.go index d0598a8..457c801 100644 --- a/api_test.go +++ b/api_test.go @@ -42,3 +42,14 @@ func TestInvalidMustCompilePanics(t *testing.T) { }() MustCompile("not a valid expression") } + +func TestFunctionToObject(t *testing.T) { + assert := assert.New(t) + var j = []byte(`{"name":"John","test":{"js":"{\"age\": 26, \"city\": \"BeiJin\"}"},"nested_json":"{\"age\": 25, \"city\": \"NewYork\"}"}`) + var d interface{} + err := json.Unmarshal(j, &d) + assert.Nil(err) + result, err := Search("[name,to_object(test.js).city,to_object(nested_json).city]", d) + assert.Nil(err) + assert.Equal([]interface{}{"John", "BeiJin", "NewYork"}, result) +} diff --git a/functions.go b/functions.go index e9770e8..cdbdb32 100644 --- a/functions.go +++ b/functions.go @@ -318,6 +318,13 @@ func newFunctionCaller() *functionCaller { }, handler: jpfNotNull, }, + "to_object": { + name: "to_object", + arguments: []argSpec{ + {types: []jpType{jpString}}, + }, + handler: jpfToObject, + }, } return caller } @@ -839,3 +846,13 @@ func jpfNotNull(arguments []interface{}) (interface{}, error) { } return nil, nil } + +func jpfToObject(arguments []interface{}) (interface{}, error) { + v := arguments[0].(string) + var obj interface{} + err := json.Unmarshal([]byte(v), &obj) + if err != nil { + return nil, errors.New("invalid json string") + } + return obj, nil +}