【问题标题】:JSON nest to be removed from just one list仅从一个列表中删除 JSON 嵌套
【发布时间】:2021-09-03 12:34:24
【问题描述】:

我的 JSON 内容如下所示:

    myJSON = '{
    "GeneralInputs":
    [
    {"apples":12,"pears":41},
    {"apples":13,"pears":42}
    ],
    
    "Assumptions":
    ["jabberwocky.json"]
    }'

但我需要删除 ["jabberwocky.json"] 周围的 []

这是由下游使用其他人的代码决定的。

我试过了……

https://stackoverflow.com/questions/17164715/how-to-remove-a-level-of-lists-from-a-list-of-lists but this applies to all the lists.

..和...

before = ":[\"jabberwocky.json\"]}"
after = ":\"jabberwocky.json\"}"

str_replace(myJSON, before, after)

如何仅在两个列表之一上执行此操作??

BR

【问题讨论】:

    标签: r json dplyr


    【解决方案1】:

    不确定这是多么普遍,但仍然:

    library(jsonlite)
    new_json <- toJSON(fromJSON(myJSON),
                       auto_unbox = TRUE,
                       pretty = TRUE)
    

    给予:

    {
      "GeneralInputs": [
        {
          "apples": 12,
          "pears": 41
        },
        {
          "apples": 13,
          "pears": 42
        }
      ],
      "Assumptions": "jabberwocky.json"
    }
    

    【讨论】:

    • ... 就在后面... 有另一个超级简单的答案,很有效!非常感谢
    【解决方案2】:

    你可以试试-

    before = "[\"jabberwocky.json\"]"
    after = "jabberwocky.json"
    
    stringr::str_replace(myJSON, fixed(before), after)
    #In base R use sub
    #sub(before, after, myJSON, fixed = TRUE)
    
    #[1] "{\n\"GeneralInputs\":\n[\n{\"apples\":12,\"pears\":41},\n{\"apples\":13,\"pears\":42}\n],\n\n\"Assumptions\":\njabberwocky.json\n}"
    

    使用cat 进行显示 -

    cat(str_replace(myJSON, fixed(before), after))
    #{
    #"GeneralInputs":
    #[
    #{"apples":12,"pears":41},
    #{"apples":13,"pears":42}
    #],
    #
    #"Assumptions":
    #jabberwocky.json
    #}
    

    【讨论】:

    • 好的 - 8 分钟的回复......非常令人印象深刻的 stringr 完美地工作。我做了一个小改动,在 = "\"jabberwocky.json\"" 之后添加了一组引号,非常感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-21
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    • 2019-03-22
    相关资源
    最近更新 更多