Skip to content

Instantly share code, notes, and snippets.

@cpsievert
Created December 22, 2017 18:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cpsievert/04d53edbe902ca86a41949e24e8b4af7 to your computer and use it in GitHub Desktop.
Save cpsievert/04d53edbe902ca86a41949e24e8b4af7 to your computer and use it in GitHub Desktop.
fromJSON simplification
library(jsonlite)
txt <- '{
"points": [{
"curveNumber": 0,
"text": "a",
"pointNumber": 0,
"customdata": "c.a",
"y": 4,
"x": 1
}, {
"curveNumber": 1,
"text": "w",
"pointNumber": 0,
"customdata": "c.w",
"y": 9,
"x": 1
}]
}'
# the desired "return value"
str(fromJSON(txt))
#> List of 1
#> $ points:'data.frame': 2 obs. of 6 variables:
#> ..$ curveNumber: int [1:2] 0 1
#> ..$ text : chr [1:2] "a" "w"
#> ..$ pointNumber: int [1:2] 0 0
#> ..$ customdata : chr [1:2] "c.a" "c.w"
#> ..$ y : int [1:2] 4 9
#> ..$ x : int [1:2] 1 1
txt2 <- '
{"output":{"id":"hover-data","property":"children"},"inputs":[{"id":"basic-interactions","property":"hoverData","value":{"points":[{"curveNumber":0,"pointNumber":0,"x":1,"y":4,"customdata":"c.a","text":"a"},{"curveNumber":1,"pointNumber":0,"x":1,"y":9,"customdata":"c.w","text":"w"}]}}]}
'
# due simplification rules, we get an awkward return value
str(fromJSON(txt2)$inputs$value)
#> 'data.frame': 1 obs. of 1 variable:
#> $ points:List of 1
#> ..$ :'data.frame': 2 obs. of 6 variables:
#> .. ..$ curveNumber: int 0 1
#> .. ..$ pointNumber: int 0 0
#> .. ..$ x : int 1 1
#> .. ..$ y : int 4 9
#> .. ..$ customdata : chr "c.a" "c.w"
#> .. ..$ text : chr "a" "w"
# we can, however, avoid simplication at first, obtain the 'return' value,
# then simplify it
value <- fromJSON(txt2, simplifyVector = FALSE)$inputs[[1]]$value
str(jsonlite:::simplify(value))
#> List of 1
#> $ points:'data.frame': 2 obs. of 6 variables:
#> ..$ curveNumber: int [1:2] 0 1
#> ..$ pointNumber: int [1:2] 0 0
#> ..$ x : int [1:2] 1 1
#> ..$ y : int [1:2] 4 9
#> ..$ customdata : chr [1:2] "c.a" "c.w"
#> ..$ text : chr [1:2] "a" "w"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment