gather_object: Gather a JSON object into name-value pairs

gather_objectR Documentation

Gather a JSON object into name-value pairs

Description

gather_object collapses a JSON object into name-value pairs, creating a new column 'name' to store the pair names, and storing the values in the 'JSON' attribute for further tidyjson manipulation. All other columns are duplicated as necessary. This allows you to access the names of the object pairs just like gather_array lets you access the values of an array.

Usage

gather_object(.x, column.name = default.column.name)

Arguments

.x

a JSON string or tbl_json object whose JSON attribute should always be an object

column.name

the name to give to the column of pair names created

Details

gather_object is often followed by enter_object to enter into a value that is an object, by append_values to append all scalar values as a new column or json_types to determine the types of the values.

Value

a tbl_json object

See Also

gather_array to gather a JSON array, enter_object to enter into an object, gather to gather name-value pairs in a data frame

Examples


# Let's start with a very simple example
json <- '{"name": "bob", "age": 32, "gender": "male"}'

# Check that this is an object
json %>% json_types

# Gather object and check types
json %>% gather_object %>% json_types

# Sometimes data is stored in object pair names
json <- '{"2014": 32, "2015": 56, "2016": 14}'

# Then we can use the column.name argument to change the column name
json %>% gather_object("year")

# We can also use append_values_number to capture the values, since they are
# all of the same type
json %>% gather_object("year") %>% append_values_number("count")

# This can even work with a more complex, nested example
json <- '{"2015": {"1": 10, "3": 1, "11": 5}, "2016": {"2": 3, "5": 15}}'
json %>% gather_object("year") %>% gather_object("month") %>%
  append_values_number("count")

# Most JSON starts out as an object (or an array of objects), and
# gather_object can be used to inspect the top level (or 2nd level) objects
library(dplyr)
worldbank %>% gather_object %>% json_types %>% count(name, type)

tidyjson documentation built on Jan. 7, 2023, 1:14 a.m.