0

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:

df

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).

dfrankow
  • 20,191
  • 41
  • 152
  • 214

2 Answers2

1

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.

Bas
  • 4,628
  • 1
  • 14
  • 16
0
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
nurandi
  • 1,588
  • 1
  • 11
  • 20