关于jsonlite包fromJSON函数JSON到R类型映射的疑问
jsonlite::fromJSON() Behavior with Your JSON Example Hey there! Let's unpack your questions about how jsonlite maps JSON structures to R data types—this is a common point of confusion, so let's break it down with your specific example.
1. Why are cars parsed as a data.frame and models as a list?
Let's look at your JSON structure again:
{"cars": [ {"models" : [ {"type":"Fiesta"} ] } ] }
- The
carsarray contains objects with consistent structure (each object has exactly one key:models). By default,fromJSON()simplifies such arrays into data.frames, since each object can be treated as a row with columns matching the object's keys. That's whydata$carsis a data.frame with one column namedmodels. - The
modelsvalue in eachcarsobject is itself a JSON array ([{"type":"Fiesta"}]). Since this array contains an object (not simple values like strings/numbers), and it's stored as a column in thecarsdata.frame,jsonlitecan't simplify it into a regular vector (data.frame columns need to be vectors or lists). Instead, it keeps this as a list column—each entry in themodelscolumn is a list representing the inner JSON array.
2. What are the rules for mapping JSON entities to R types?
jsonlite uses a set of heuristics (controlled mainly by the simplifyVector argument, which defaults to TRUE) to decide how to convert JSON to R types:
- JSON objects (key-value pairs):
- If all values are of consistent length/structure (e.g., each value is an array of the same length, or a scalar), they're converted to a data.frame (columns = object keys, rows = values).
- If values are mixed (e.g., some scalars, some arrays of different lengths), they're converted to a named list.
- JSON arrays:
- If all elements are simple values (strings, numbers, booleans, NULL) of the same type, converted to an R vector.
- If all elements are objects with identical key sets, converted to a data.frame (each object = row, keys = columns).
- If elements are mixed types, or arrays (like your
modelsarray), converted to an R list.
- When
simplifyVector = FALSE, all JSON structures are converted to nested lists with no simplification—this is useful if you want to preserve the exact JSON hierarchy.
3. Why does names(data$cars$models) return NULL?
data$cars$models is a list where each element corresponds to the models array from a cars object. In your case, it's a list of length 1, and that single element is another list (list(type = "Fiesta")).
The reason names(data$cars$models) is NULL is because JSON arrays are ordered, unlabeled collections—they don't have keys for their elements. So when jsonlite parses the models JSON array into an R list, that list doesn't have names attached to its elements. If you want to access the type value, you'd use:
data$cars$models[[1]]$type
This drills into the first element of the models list, then accesses the named type entry inside that inner list.
内容的提问来源于stack exchange,提问作者Pioggia_91

