R语言 不带外方括号的toJSON

dauxcl2d  于 2023-06-19  发布在  其他
关注(0)|答案(3)|浏览(203)

我正在使用jsonlite中的toJSON()将特定结构的嵌套列表(API所需)转换为JSON。但是,我需要最终的JSON不包含外部方括号(API也需要)。

  1. test_list <- list(
  2. list(formName = "test_title", user_id = "test_userid", rows = list(list(row = 0))),
  3. list(formName = "test_title2", user_id = "test_userid2", rows = list(list(row = 0)))
  4. )
  5. jsonlite::toJSON(test_list, pretty = TRUE, auto_unbox = TRUE)

其给出:

  1. [
  2. {
  3. "formName": "test_title",
  4. "user_id": "test_userid",
  5. "rows": [
  6. {
  7. "row": 0
  8. }
  9. ]
  10. },
  11. {
  12. "formName": "test_title2",
  13. "user_id": "test_userid2",
  14. "rows": [
  15. {
  16. "row": 0
  17. }
  18. ]
  19. }
  20. ]

但是我需要去掉第一个和最后一个方括号。
我可以使用purrr::flatten()来删除列表的顶层,从而删除JSON中的方括号,但是toJSON()似乎不喜欢列表中有重复的名称,并将它们重命名为name.1,name.2,name.3等(API也不允许)。
即:

  1. jsonlite::toJSON(test_list %>% purrr::flatten(), pretty = TRUE, auto_unbox = TRUE)

它删除了外部方括号,但将第二个元素中的名称转换为formName.1,user_id.1,rows.1,如下所示:

  1. {
  2. "formName": "test_title",
  3. "user_id": "test_userid",
  4. "rows": [
  5. {
  6. "row": 0
  7. }
  8. ],
  9. "formName.1": "test_title2",
  10. "user_id.1": "test_userid2",
  11. "rows.1": [
  12. {
  13. "row": 0
  14. }
  15. ]
  16. }

但这是我需要的

  1. {
  2. "formName": "test_title",
  3. "user_id": "test_userid",
  4. "rows": [
  5. {
  6. "row": 0
  7. }
  8. ],
  9. "formName": "test_title2",
  10. "user_id": "test_userid2",
  11. "rows": [
  12. {
  13. "row": 0
  14. }
  15. ]
  16. }

也就是说,第二个JSON元素中的formName、user_ud和rows不追加“.1”
任何建议将不胜感激!

klsxnrf1

klsxnrf11#

这似乎是可行的(丑陋但简单):

  1. df = data.frame(a=1,b=2)
  2. js = toJSON(unbox(fromJSON(toJSON(df))))
  3. > js
  4. {"a":1,"b":2}

由于某些原因,auto_unbox=T不起作用:

  1. > toJSON(df,auto_unbox = T)
  2. [{"a":1,"b":2}]
uqcuzwp8

uqcuzwp82#

编辑JSON。您可以使用gsubstringr来执行此操作。如果你使用stringr函数,它将丢失它的"json"类,但你可以把它放回去:

  1. > x = jsonlite::toJSON(test_list %>% purrr::flatten(), pretty = TRUE, auto_unbox = TRUE)
  2. > gsub("user_id\\.1", "user_id", x)
  3. {
  4. "formName": "test_title",
  5. "user_id": "test_userid",
  6. "rows": [
  7. {
  8. "row": 0
  9. }
  10. ],
  11. "formName.1": "test_title2",
  12. "user_id": "test_userid2",
  13. "rows.1": [
  14. {
  15. "row": 0
  16. }
  17. ]
  18. }
  19. > y = stringr::str_replace_all(x, "user_id\\.1", "user_id")
  20. > class(y) = "json"
  21. > y
  22. {
  23. "formName": "test_title",
  24. "user_id": "test_userid",
  25. "rows": [
  26. {
  27. "row": 0
  28. }
  29. ],
  30. "formName.1": "test_title2",
  31. "user_id": "test_userid2",
  32. "rows.1": [
  33. {
  34. "row": 0
  35. }
  36. ]
  37. }

我将留给您编写适当的正则表达式来进行所需的替换。

展开查看全部
c0vxltue

c0vxltue3#

它现在真的起作用了。Auto_Unbox对我很有用。

相关问题