R:导入错误列的JSON数据

时间:2016-11-18 21:28:34

标签: json r

我使用rjson库导入了一些JSON数据。我面临的问题是某些数据似乎未对齐。我怀疑这是由于缺少值。 如何检测并重新排列错误列中的数据并使用NULL填充空值。我无法分享数据。我希望图像足够了。 enter image description here

用于导入数据的代码:

library(rjson)
json_data <- do.call(rbind, lapply(readLines(training.file$filepaths[ind]), rjson::fromJSON))
json_data <- as.data.frame(json_data)

我也尝试过使用jsonlite :: fromJSON函数而不是rjson :: fromJSON,但是得到以下错误

 Error in feed_push_parser(readBin(con, raw(), n), reset = TRUE) : 
  parse error: trailing garbage
          d_str": null, "place": null} {"truncated": false, "text": "R
                     (right here) ------^

json文件格式(数据被操纵,但此示例中存在所有属性):

{
    "truncated": false, "text": "abc abc", "in_reply_to_status_id": null,
     "id": 123, "favorite_count": 0, "retweeted": false, "entities": {
        "symbols": [], "user_mentions": [], "hashtags": [], "urls": []
        }, 
    "in_reply_to_screen_name": null, "id_str": "123", "retweet_count": 0,
    "in_reply_to_user_id": null, "screen_name_statistics": {
         "has_underscore": true, "contains_swear": false, "has_digits": false, 
        "contains_condition": false, "has_chars": true
    }, 
    "user": {
        "verified": false, "geo_enabled": false, "followers_count": 0,
        "utc_offset": -14400, "statuses_count": 17600, "friends_count": 4425, 
        "lang": "en", "favourites_count": 1900, "screen_name": "1name1",
        "url": null, "created_at": "Sat Jun 00 03:36:27 +0000 2012",
        "time_zone": "Atlantic Time (Canada)", "listed_count": 2
    }, 
    "geo": null, "in_reply_to_user_id_str": null, "lang": "en",
    "created_at": "Mon Nov 55 05:18:49 +0000 2013",
    "in_reply_to_status_id_str": null, "place": null
}

更多信息:

obj1和obj2包含不同数量的属性obj1 contains 19 properties while obje contains 20 properties

使用as.data.frame将列表转换为数据帧时,会出现

错位。可能需要自定义函数来考虑属性名称。

1 个答案:

答案 0 :(得分:0)

我使用rjson :: fromJson函数导入数据。这是作为列表导入的,然后我使用as.data.frame将其转换为数据帧以进行进一步分析。

起初我没有注意到json对象具有不同数量的属性,导致数据帧中的数据不对齐。列名称不匹配。

为了解决这个问题,我编写了一个自定义映射函数,该函数查看列表中的各个值并将它们映射到预定义的数据框中。

特定于我的示例的代码here 。具体来说,“importJSON”函数处理列表到数据帧的映射。