【问题标题】:R: JSON data imported into wrong columnsR:JSON数据导入错误的列
【发布时间】:2016-11-18 21:28:33
【问题描述】:

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

用于导入数据的代码:

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 将列表转换为数据帧时会发生错位。可能需要自定义函数来考虑属性名称。

【问题讨论】:

  • 请发布您的 JSON
  • @HubertL 添加了有问题的代码 sn-p。这会从一个文件中读取所有数据。文件每行包含一个扁平化的 json 对象。
  • 如果没有看到您的 JSON,就不可能回答您的问题。但是,我建议改用library(jsonlite)。有关示例,请参见 this answer
  • @SymbolixAU 当我使用 jsonlite::fromJSON 时,我收到以下错误“feed_push_parser 中的错误(readBin(con, raw(), n), reset = TRUE):解析错误:尾随垃圾 d_str ": null, "place": null} {"截断": false, "text": "R (就在这里) ------^"
  • 看起来您正在逐行阅读,但行与行之间缺少逗号。在这种情况下,请使用look at this answer

标签: json r


【解决方案1】:

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

起初我没有注意到 json 对象具有不同数量的属性,这会导致数据框中的数据错位。列名不匹配。

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

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

【讨论】:

  • 很高兴你能成功。仅供参考,要从 StackOverflow 获得好的答案,您确实需要 make a reproducible example,包括其他人可以使用的示例数据。
猜你喜欢
  • 2013-12-13
  • 2012-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-29
  • 2017-06-03
  • 2013-03-14
  • 1970-01-01
相关资源
最近更新 更多