【问题标题】:Reading JSON with id outside curly brackets and no quotation marks读取带有大括号外 id 且没有引号的 JSON
【发布时间】:2021-12-29 21:02:42
【问题描述】:

我在使用以下格式将 json 文件导入 R 时遇到了一些问题:

C135-HR2459 {"number_a": 1, "number_b":2} 
C156-HR2249 {"number_a": 1, "number_b":2} 

如果它具有以下格式,它将起作用:

{"id": C135-HR2459, "number_a": 1, "number_b":2} 
{"id": C156-HR2249, "number_a": 1, "number_b":2} 

【问题讨论】:

    标签: r json import notepad++


    【解决方案1】:

    您可能希望使用 readLines 将其作为纯文本读取,然后在尝试读取为 JSON 之前使用正则表达式对其进行处理。

    先去掉错位的"{",然后在每个元素的开头加上'{"id: "'

    sub("^", "{id: ", sub("\\{", "", txt))
    [1] "{id: C135-HR2459\t\"number_a\": 1, \"number_b\":2}" "{id: C156-HR2249\t\"number_a\": 1, \"number_b\":2}"
    

    内部"{"的消除是由“内部sub”完成的。R函数需要从内到外阅读理解。

    【讨论】:

      【解决方案2】:

      使用正则表达式,您可以搜索:

      C(.*?)\-HR(.*?) \{(.*?)\}
      

      并将其替换为:

      \{\"id\"\:\"C\1\-HR\2\", \3 \}
      

      请注意,结果将是:

      {"id":"C135-HR2459", "number_a": 1, "number_b":2 } 
      {"id":"C156-HR2249", "number_a": 1, "number_b":2 } 
      

      在哪里

      id 的值必须在 "" 之间,因为它是一个字符串

      这里也有这个:

      {"id": C135-HR2459, "number_a": 1, "number_b":2} 
      {"id": C156-HR2249, "number_a": 1, "number_b":2} 
      

      不是一个有效的json,因为id值不在引号之间

      【讨论】:

        【解决方案3】:

        使用 Notepad++,你可以做到:

        • Ctrl+H
        • 查找内容:^(\S+) {
        • 替换为:{"id": "$1",
        • 检查 环绕
        • CHECK 正则表达式
        • 取消选中 . matches newline
        • 全部替换

        说明:

        ^           # beginning of line
        (\S+)       # group 1, 1 or more non space character; you can use (.+?) if the string contains spaces
                    # 1 space
        {           # open curly brace
        

        替换:

        {"id": "    # literally
        $1          # content of group 1
        ",          # literally, there is a space after the comma
        

        屏幕截图(之前):

        截图(之后):

        【讨论】:

          猜你喜欢
          • 2019-03-17
          • 1970-01-01
          • 2012-10-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2016-07-17
          相关资源
          最近更新 更多