json-pointer
json-pointer copied to clipboard
#dict is not working with empty arrays
dict doesn't return property if its value is an empty array, but #has checks that it exists.
jsp = require "json-pointer"
console.dir jsp.has { a: "x", b: [] }, "/b"
console.dir jsp.dict { a: "x", b: [] }
returns:
true
{ '/a': 'x' }
Hmm, i agree it's inconsistent. How should we solve it?
The idea of dict was to return a jsonpointer/value map. I'm not sure if we should include empty arrays.
I think it should be easy to create an object with #dict, process it and apply the values to an other object using #set. If we include empty arrays the result will depend on the order the values are applied.
Maybe the best option is to deprecate #has since this can be easily achieved by #get.
I think that #dict
should return a path for an empty array because it is a valid path, it exists in object and it's value isn't undefined
. That is all props that are not equal to undefined must be returned by #dict
as deep as possible. I tried to fix it in this pull request
But I agree with you according #has
method since it useless (personally I never had cases where #has
had advantages over the #get
)
What about non empty arrays and objects?
{
arr: [1],
obj: { example: 4 }
}
To have a consistent behaviour #dict
should return the following:
{
'/arr': [1],
'/arr/0': 1,
'/obj': { example: 4 },
'/obj/example': 4
}
In the case above /arr
and /obj
are also valid path that exist and their values are not undefined
. We could change it to behave like that, but i am not sure yet if this it's a good idea.
I agree with you and although both /arr/0
and /arr
paths are not undefined
, /arr/0
path is deeper then /arr
so it must be returned by #dict
(and my opinion that /arr
shouldn't be returned in that case).
So my vote for:
{
'/arr/0': 1,
'/obj/example': 4
}
Ok, convinced.
I think the iteration functionality should be moved from #dict
to #walk
.
So #dict
can just #walk
and return only the deepest values.
#walk
should execute the callback for every json-pointer, not just the deepest ones. We could add an optional descend callback to #walk
that defaults to:
(value) ->
type = {}.toString.call(value)
type == '[object Object]' or type == '[object Array]'
And #has
gets removed.
What do you think about this changes?
Nice, waiting for update!
Any progress on this issue? Actually I'm waiting for the fix or if it is not possible to complete in near future, please merge my pull request, and publish new version in npm.
@manuelstofer I'm still waiting when you fix this issue and update npm package