如何在json中填充空元素

时间:2015-04-21 16:12:06

标签: r

我有一个奇怪的json文件,其中一些行元素总共丢失了。我尝试用NA填充它们或null但我不能瞄准它。

以下是这种情况的一个例子 json的例子:

require(RJSONIO)    

json_file <-  '[{"name":"Doe, John","group":"Red","age (y)":24,"height (cm)":182,"wieght (kg)":74.8},
    {"name":"Doe, Jane","group":"Green","age (y)":30,"height (cm)":170,"wieght (kg)":70.1,"score":500},
    {"name":"Smith, Joan","age (y)":41,"height (cm)":169,"wieght (kg)":60,"score":null},
    {"name":"Brown, Sam","group":"Green","age (y)":22,"height (cm)":183,"wieght (kg)":75,"score":865},
    {"name":"Jones, Larry","group":"Green","age (y)":31,"height (cm)":178,"wieght (kg)":83.9,"score":221},
    {"name":"Murray, Seth","group":"Red","age (y)":35,"height (cm)":172,"wieght (kg)":76.2},
    {"name":"Doe, Jane","group":"Yellow","age (y)":22,"height (cm)":164,"wieght (kg)":68,"score":902}]'


json_file <- fromJSON(json_file)

从第一行开始,它缺少第3行的分数标签,缺少组标签,第6行缺少分数。

Json有更多级别:

[
    {
      "id": 1,
      "name": "Lora",
      "surname": "Ann",
      "time": 30,
      "light": {
        "full": 4,
      },
      "height": {
        "id": 156,
        "weight": {
          "pounds": 88,
        }
      }
    },
    {
      "id": 2,
      "name": "Ann",
      "surname": "Lora",
      "light": {
        "full": 2,
      },
      "height": {
        "id": 173,
        "weight": {
          "pounds": 55,
          "kilo": 56,
        }
      }
    }
]

1 个答案:

答案 0 :(得分:0)

jsonlite会将其转换为数据框并自动为您填写缺失值的NAs。

require(jsonlite)
json_file <- fromJSON(json_file)

          name  group age (y) height (cm) wieght (kg) score
1    Doe, John    Red      24         182        74.8    NA
2    Doe, Jane  Green      30         170        70.1   500
3  Smith, Joan   <NA>      41         169        60.0    NA
4   Brown, Sam  Green      22         183        75.0   865
5 Jones, Larry  Green      31         178        83.9   221
6 Murray, Seth    Red      35         172        76.2    NA
7    Doe, Jane Yellow      22         164        68.0   902


> fromJSON(json_file2, flatten = TRUE)
  id name surname time light.full height.id height.weight.pounds height.weight.kilo
1  1 Lora     Ann   30          4       156                   88                 NA
2  2  Ann    Lora   NA          2       173                   55                 56
> fromJSON(json_file2, flatten = FALSE)
  id name surname time full height.id height.weight.pounds height.weight.kilo
1  1 Lora     Ann   30    4       156                   88                 NA
2  2  Ann    Lora   NA    2       173                   55                 56