使用json文件基于R中的变量删除某些数据行

时间:2018-06-02 14:36:06

标签: r json extract

我一直在使用R中的json格式文件。我试图根据变量删除不必要的数据行。例如,我正试图在

时摆脱一大堆线条
"state: incorrect" 

事件发生在以下几行:

[
{
"id": "id1",
"state": "correct",
"object": "ball",
"data": {
"http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c4"
},
"time": "2018-04-15T23:58:15.888700+00:00"
},

{
"id": "id1",
"state": "incorrect",
"object": "ball",
"data": {
  "http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c5"
},
"time": "2018-04-15T23:58:06.344300+00:00"
},

{
"id": "28s1",
"state": :"incorrect",
"object": ball",
"data": {
"http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c5"
},
"time": "2018-04-15T23:58:05.261600+00:00"
}
]

我希望有类似的东西:

[
{
"id": "id1",
"state": "correct",
"object": "ball",
"data": {
"http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c4"
},
"timeStamp": "2018-04-15T23:58:15.888700+00:00"
}
]

感谢任何评论,帮助和建议。

1 个答案:

答案 0 :(得分:2)

您的JSON字符串中有一些拼写错误,但在编辑后:

library(jsonlite)
df <- fromJSON(json_str )    
df
#     id     state object http://54&46;210&46;82&46;207/lock/public/ext/gam/type                             time
# 1  id1   correct   ball                                                     c4 2018-04-15T23:58:15.888700+00:00
# 2  id1 incorrect   ball                                                     c5 2018-04-15T23:58:06.344300+00:00
# 3 28s1 incorrect   ball                                                     c5 2018-04-15T23:58:05.261600+00:00

df <- subset(df,state!="incorrect")
toJSON(df,pretty = TRUE)
# [
#   {
#     "id": "id1",
#     "state": "correct",
#     "object": "ball",
#     "data": {
#       "http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c4"
#     },
#     "time": "2018-04-15T23:58:15.888700+00:00"
#   }
# ] 

数据

json_str <-
  '[
{
  "id": "id1",
  "state": "correct",
  "object": "ball",
  "data": {
  "http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c4"
  },
  "time": "2018-04-15T23:58:15.888700+00:00"
  },

  {
  "id": "id1",
  "state": "incorrect",
  "object": "ball",
  "data": {
  "http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c5"
  },
  "time": "2018-04-15T23:58:06.344300+00:00"
  },

  {
  "id": "28s1",
  "state": "incorrect",
  "object": "ball",
  "data": {
  "http://54&46;210&46;82&46;207/lock/public/ext/gam/type": "c5"
  },
  "time": "2018-04-15T23:58:05.261600+00:00"
  }
  ]'