Skip to content

Commit

Permalink
Merge pull request #7 from YongHee-Kim/develop
Browse files Browse the repository at this point in the history
added Base append!, pop!, deleteat! for JSONPointer. and trimed errors
  • Loading branch information
YongHee-Kim authored Jun 8, 2024
2 parents 82d38d9 + d7e678f commit 92a0d19
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 43 deletions.
2 changes: 1 addition & 1 deletion Project.toml
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
name = "JSONPointer"
uuid = "cc3ff66e-924d-4e6b-b111-1d9960e4bba9"
authors = ["김용희 <yongheekim@devsisters.com>"]
version = "0.4.0"
version = "0.4.1"

[deps]
OrderedCollections = "bac558e1-5e72-5ebc-8fee-abe8a469f55d"
Expand Down
63 changes: 40 additions & 23 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,11 @@ Implementation of JSON Pointers according to [RFC 6901](https://www.rfc-editor.o
```julia
using JSONPointer

julia>p1 = j"/a/1/b"
p2 = j"/a/2/b"
data = PointerDict(p1 =>1, p2 => 2)
PointerDict{String,Any} with 1 entry:
"a" => Any[OrderedDict{String,Any}("b"=>1), OrderedDict{String,Any}("b"=>2)]
p1 = j"/a/1/b"
p2 = j"/a/2/b"
data = PointerDict(p1 =>1, p2 => 2)
# PointerDict{String,Any} with 1 entry:
# "a" => Any[OrderedDict{String,Any}("b"=>1), OrderedDict{String,Any}("b"=>2)]

```

Expand All @@ -28,17 +28,17 @@ PointerDict{String,Any} with 1 entry:
```julia
using JSONPointer

julia> arr = [[10, 20, 30, ["me"]]]
arr[j"/1"] == [10, 20, 30, ["me"]]
arr[j"/1/2"] == 20
arr[j"/1/4"] == ["me"]
arr[j"/1/4/1"] == "me"

julia> dict = PointerDict("a" => Dict("b" => Dict("c" => [100, Dict("d" => 200)])))
dict[j"/a"]
dict[j"/a/b"]
dict[j"/a/b/c/1"]
dict[j"/a/b/c/2/d"]
arr = [[10, 20, 30, ["me"]]]
arr[j"/1"] == [10, 20, 30, ["me"]]
arr[j"/1/2"] == 20
arr[j"/1/4"] == ["me"]
arr[j"/1/4/1"] == "me"

dict = PointerDict("a" => Dict("b" => Dict("c" => [100, Dict("d" => 200)])))
dict[j"/a"]
dict[j"/a/b"]
dict[j"/a/b/c/1"]
dict[j"/a/b/c/2/d"]
```

## Advanced
Expand All @@ -53,11 +53,13 @@ julia>JSONPointer.Pointer(j"/foo/0"; shift_index = true)

You can enforce type with `::T` at the end of pointer:
```julia
p1 = j"/a::array"
p2 = j"/b/2::string"
data = PointerDict(p1 => [1,2,3], p2 => "Must be a String")
data = PointerDict(p1 => "MethodError", p2 => "Must be a String")
data = PointerDict(p1 => [1,2,3], p2 => :MethodError)
p1 = j"/a::array"
p2 = j"/b/2::string"
data = PointerDict(p1 => [1,2,3], p2 => "Must be a String")

# both of these will throw errors
data = PointerDict(p1 => "MethodError", p2 => "Must be a String")
data = PointerDict(p1 => [1,2,3], p2 => :MethodError)
```

The type `T` must be one of the six types supported by JSON:
Expand All @@ -68,12 +70,27 @@ The type `T` must be one of the six types supported by JSON:
* `::boolean`
* `::null`

### append!, deleteat!, pop! with JSONPointer
JSONPointer provides basic manipulations after the creation
```julia
p1 = j"/Root/header"

append!(p1, "id") == j"/Root/header/id"
deleteat!(p1, 1) == j"/header/id"
pop!(p1) == j"/header"
```
Note that these mutates the pointer

### String number as a key

If you need to use a string number as key for dict, put '\' in front of a number
```julia
p1 = j"/\10"
data = PointerDict(p1 => "this won't be a array")
p1 = j"/\10"
data = PointerDict(p1 => "this won't be a array")

<<<<<<< develop
data[p1]
=======
data[p1]
>>>>>>> master
```
35 changes: 25 additions & 10 deletions src/pointer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -39,11 +39,12 @@ function _last_element_to_type!(jk)
elseif x[2] == "null"
return Missing
else
error(
"You specified a type that JSON doesn't recognize! Instead of " *
"`::$(x[2])`, you must use one of `::string`, `::number`, " *
# what is most fitting error type for this?

throw(DomainError(
"`::$(x[2])`cannot be used in JSON. use one of `::string`, `::number`, " *
"`::object`, `::array`, `::boolean`, or `::null`."
)
))
end
end

Expand Down Expand Up @@ -108,7 +109,7 @@ function Pointer(token_string::AbstractString; shift_index::Bool = false)
tokens[i] += 1
end
if iszero(tokens[i])
throw(ArgumentError("Julia uses 1-based indexing, use '1' instead of '0'"))
throw(BoundsError("Julia uses 1-based indexing, use '1' instead of '0'"))
end
elseif occursin(r"^\\\d+$", token) # literal string for a number
tokens[i] = String(chop(token; head = 1, tail = 0))
Expand All @@ -120,6 +121,7 @@ function Pointer(token_string::AbstractString; shift_index::Bool = false)
end

Base.length(x::Pointer) = length(x.tokens)
Base.eachindex(x::Pointer) = eachindex(x.tokens)

Base.eltype(::Pointer{T}) where {T} = T

Expand Down Expand Up @@ -163,10 +165,10 @@ _checked_get(collection::AbstractArray, token::Int) = collection[token]
_checked_get(collection::AbstractDict, token::String) = collection[token]

function _checked_get(collection, token)
error(
throw(ArgumentError(
"JSON pointer does not match the data-structure. I tried (and " *
"failed) to index $(collection) with the key: $(token)"
)
))
end

# ==============================================================================
Expand Down Expand Up @@ -242,7 +244,7 @@ function _convert_v(v::V, p::Pointer{U}) where {U, V}
try
return convert(eltype(p), v)
catch
throw(ErrorException(
throw(ArgumentError(
"$(v)::$(typeof(v)) is not valid type for $(p). Remove type " *
"assertion in the JSON pointer if you don't a need static type."
))
Expand All @@ -266,10 +268,10 @@ function _add_element_if_needed(
end

function _add_element_if_needed(collection, token)
error(
throw(ArgumentError(
"JSON pointer does not match the data-structure. I tried (and " *
"failed) to set $(collection) at the index: $(token)"
)
))
end

_new_data(::Any, n::Int) = Vector{Any}(missing, n)
Expand All @@ -294,3 +296,16 @@ function _setindex!(collection::AbstractDict, v, p::Pointer)
return v
end

# pointer manipulation functions
function Base.append!(p::Pointer, token::Union{String, Int})
push!(p.tokens, token)
return p
end
function Base.deleteat!(p::Pointer, index::Int)
deleteat!(p.tokens, index)
return p
end
function Base.pop!(p::Pointer)
pop!(p.tokens)
return p
end
42 changes: 33 additions & 9 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ end
@test_throws ArgumentError JSONPointer.Pointer("some/thing")
doc = [0, 1, 2]
@test_throws(
ErrorException(
ArgumentError(
"JSON pointer does not match the data-structure. I tried (and " *
"failed) to index $(doc) with the key: a"
),
Expand Down Expand Up @@ -201,7 +201,7 @@ end

@testset "Failed setindex!" begin
d = PointerDict("a" => [1])
@test_throws ErrorException d[j"/a/b"] = 1
@test_throws ArgumentError d[j"/a/b"] = 1
end

@testset "grow object and array" begin
Expand All @@ -228,8 +228,8 @@ end
@test data[p1] == "string"
@test data[p2] == 1

@test_throws ErrorException data[p1] = 1
@test_throws ErrorException data[p2] = "string"
@test_throws ArgumentError data[p1] = 1
@test_throws ArgumentError data[p2] = "string"

d = PointerDict(p1 =>missing, p2 => missing, p3 => missing, p4 => missing, p5 => missing)
@test d[p1] == ""
Expand All @@ -241,12 +241,12 @@ end

@testset "Exceptions" begin
# error on undefined datatype
@test_throws ErrorException JSONPointer.Pointer("/a::nothing")
@test_throws ErrorException JSONPointer.Pointer("/a/1::Int")
@test_throws DomainError JSONPointer.Pointer("/a::nothing")
@test_throws DomainError JSONPointer.Pointer("/a/1::Int")

# error for 0 based indexing
@test_throws ArgumentError JSONPointer.Pointer("/0")
@test_throws ArgumentError JSONPointer.Pointer("/a/0")
@test_throws BoundsError JSONPointer.Pointer("/0")
@test_throws BoundsError JSONPointer.Pointer("/a/0")
@test isa(JSONPointer.Pointer("/0"; shift_index = true), JSONPointer.Pointer)

end
Expand Down Expand Up @@ -310,4 +310,28 @@ end
arr = [1,2,3]
haskey(arr, j"/1")
!haskey(arr, j"/4")
end
end

@testset "append!, deleteat!, pop! for JSONPointer " begin
p1 = j"/Root/header"
p2 = j"/Root/Array/1"
p3 = j"/Root/Array/2/id"
p4 = j"/Root/Array/3/comments/1"

# appendc! tests
@test append!(p1, "id") == j"/Root/header/id"
@test deleteat!(p1, 1) == j"/header/id"
@test pop!(p1) == j"/header"

@test append!(p2, "somelongvalues") == j"/Root/Array/1/somelongvalues"
@test deleteat!(p2, 2) == j"/Root/1/somelongvalues"
@test pop!(p2) == j"/Root/1"

@test append!(p3, 1) == j"/Root/Array/2/id/1"
@test deleteat!(p3, 3) == j"/Root/Array/id/1"
@test pop!(p3) == j"/Root/Array/id"

@test append!(p4, 2) == j"/Root/Array/3/comments/1/2"
deleteat!(p4, 5) == j"/Root/Array/3/comments/2"
@test pop!(p4) == j"/Root/Array/3/comments"
end

6 comments on commit 92a0d19

@YongHee-Kim
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request created: JuliaRegistries/General/108519

Tip: Release Notes

Did you know you can add release notes too? Just add markdown formatted text underneath the comment after the text
"Release notes:" and it will be added to the registry PR, and if TagBot is installed it will also be added to the
release that TagBot creates. i.e.

@JuliaRegistrator register

Release notes:

## Breaking changes

- blah

To add them here just re-invoke and the PR will be updated.

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.4.1 -m "<description of version>" 92a0d198703fd4559210885e1eefdb4b0e769beb
git push origin v0.4.1

@YongHee-Kim
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator register

Release notes:

  • Added Base.append!, Base.deleteat!, Base.pop! for a JSONPointer, for convenience
  • Changed some error types

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request updated: JuliaRegistries/General/108519

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.4.1 -m "<description of version>" 92a0d198703fd4559210885e1eefdb4b0e769beb
git push origin v0.4.1

@YongHee-Kim
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Error while trying to register: Version 0.4.1 already exists

Please sign in to comment.