I am trying to parse json using jsonlite::fromJSON, and all sorts of crazy stuff comes back. This question shows one example where I give json in a file ( blarg.json
), and examine the return value. To repeat:
blarg.json
file:
[{ "id": 211,
"sub_question_skus": { "0": 329, "behavior": 216 } },
{ "id": 333,
"sub_question_skus": [ 340, 341 ] },
{ "id": 345,
"sub_question_skus": [ 346, 352 ] },
{ "id": 444,
"sub_question_skus": null }]
Code:
library(jsonlite)
df <- fromJSON('blarg.json')
Data frame with embedded lists and vectors in the RStudio viewer:
How do I create this exact data frame from that question in simple R code, without using jsonlite? It would help me create test cases.
Bonus if it can create code from a data frame automatically (like "SHOW SELECT" in SQL).
You are looking for dput()
.
Read How to make a great R reproducible example for more information on that function and other tips on making a reproducible example.
data.frame(id = df$id,
x = unlist(sapply(df$sub_question_skus, function(i) ifelse(is_empty(i[1]), NA, i[1]))),
y = unlist(sapply(df$sub_question_skus, function(i) ifelse(is_empty(i[2]), NA, i[2]))) )
# id x y
# 1 211 329 216
# 2 333 340 341
# 3 345 346 352
# 4 444 NA NA
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.