How do I remove extra brackets in this simple tibble to JSON conversion code block?

81 views Asked by At

If I run the code at the bottom of this post, I get the json text below. How do I get rid of the [ and ] in the data section of the json, but not the fun_example part? Rather than fix up the JSON after convesion from list to JSON, I would prefer a solution that identifies what data I need to input to get jsonlite to do the conversion directly in the manner desired.

Current Output:

{
  "data": {
      "a": [
        {
          "second": 1
        },
        {
          "second": 2
        }
      ],
      "b": [
        {
          "second": 1
        },
        {
          "second": 2
        }
      ]
    },
  "fun_example": [
    {
      "hi": 1,
      "world": 2
    }
  ]
}

Desired Output:

{
  "data": {
      "a": 
        {
          "second": 1
        },
        {
          "second": 2
        }
      ,
      "b": 
        {
          "second": 1
        },
        {
          "second": 2
        }
      
    },
  "fun_example": [
    {
      "hi": 1,
      "world": 2
    }
  ]
}

Code:

list(
  data = tibble::tibble(
    first = c("a", "a", "b", "b"),
    second = c(1, 2, 1, 2)
  ) |>
    tidyr::nest(.by = first) |>
    tidyr::pivot_wider(
      names_from = first,
      values_from = data
    ) |>
    jsonlite::unbox(),
  fun_example=tibble(hi=1,
                     world=2)
)|>
  jsonlite::toJSON(pretty = T, auto_unbox = T)
1

There are 1 answers

0
Near Lin On

Why do you want to remove brackets in part a and b? If you apply fromJSON to this list, the result would be:

$data
$data$a
  second
1      1
2      2

$data$b
  second
1      1
2      2


$fun_example
  hi world
1  1     2

[{}] is the form of simplifyDataFrame in jsonlite, remove the brackets may cause error.