enter_object: Enter into a specific object and discard all other JSON data

View source: R/enter_object.R

enter_objectR Documentation

Enter into a specific object and discard all other JSON data

Description

When manipulating a JSON object, enter_object lets you navigate to a specific value of the object by referencing it's name. JSON can contain nested objects, and you can pass in more than one character string into enter_object to navigate through multiple objects simultaneously.

Usage

enter_object(.x, ...)

Arguments

.x

a json string or tbl_json object

...

a quoted or unquoted sequence of strings designating the object name or sequences of names you wish to enter

Details

After using enter_object, all further tidyjson calls happen inside the referenced object (all other JSON data outside the object is discarded). If the object doesn't exist for a given row / index, then that row will be discarded.

In pipelines, enter_object is often preceded by gather_object and followed by gather_array if the value is an array, or spread_all if the value is an object.

Value

a tbl_json object

See Also

gather_object to find sub-objects that could be entered into, gather_array to gather an array in an object and spread_all or spread_values to spread values in an object.

Examples


# Let's start with a simple example of parents and children
json <- c('{"parent": "bob",  "children": ["sally", "george"]}',
          '{"parent": "fred", "children": ["billy"]}',
          '{"parent": "anne"}')

# We can see the names and types in each
json %>% gather_object %>% json_types

# Let's capture the parent first and then enter in the children object
json %>% spread_all %>% enter_object(children)

# Also works with quotes
json %>% spread_all %>% enter_object("children")

# Notice that "anne" was discarded, as she has no children

# We can now use gather array to stack the array
json %>% spread_all %>% enter_object(children) %>%
  gather_array("child.num")

# And append_values_string to add the children names
json %>% spread_all %>% enter_object(children) %>%
  gather_array("child.num") %>%
  append_values_string("child")

# The path can be comma delimited to go deep into a nested object
json <- '{"name": "bob", "attributes": {"age": 32, "gender": "male"}}'
json %>% enter_object(attributes, age)

# A more realistc example with companies data
library(dplyr)
companies %>%
  enter_object(acquisitions) %>%
  gather_array %>%
  spread_all %>%
  glimpse

jeremystan/tidyjson documentation built on Feb. 4, 2023, 6:54 p.m.