从R

时间:2018-07-14 19:29:10

标签: r json jsonlite

我正在尝试在R中制作以下JSON:

test_json <- '{
"PropertyValues": [{"PropertyDef": 100,
  "TypedValue": {
  "DataType": 9,
  "HasValue": false,
  "Value": null,
  "Lookup": {
  "Deleted": false,
  "DisplayValue": null,
  "Hidden": false,
  "Item": 1,
  "Version": -1
  },
  "Lookups": null,
  "DisplayValue": null,
  "SortingKey": null,
  "SerializedValue": null
  }
},
  {
  "PropertyDef": 0,
  "TypedValue": {
  "DataType": 1,
  "HasValue": false,
  "Value": "my test document",
  "Lookup": null,
  "Lookups": null,
  "DisplayValue": null,
  "SortingKey": null,
  "SerializedValue": null
  }
  }
  ],
  "Files": [
  {
  "UploadID": 1,
  "Title": null,
  "Extension": "txt",
  "Size": 27
  }
  ]
  }'

这是我尝试从列表对象和使用jsonlite包制作JSON的方式:

create_object <- function(){
  json_query <- list(
    PropertyValues = list(
      PropertyDef = 100,
      TypedValue = list(
        DataType = 9,
        HasValue = FALSE,
        Value = NA,
        Lookup = list(
          Deleted = FALSE,
          DisplayValue = NA,
          Hidden = FALSE,
          Item = 6,
          Version = -1
        ),
        Lookups = NA,
        DisplayValue = NA,
        SortingKey = NA,
        SerializedValue = NA
      ),
      PropertyDef = 0,
      TypedValue = list(
        DataType = 1,
        HasValue = FALSE,
        Value = "090216ba8014f3be",
        Lookup = NA,
        Lookups = NA,
        DisplayValue = NA,
        SortingKey = NA,
        SerializedValue = NA
      )
    ),
    Files = list(
      UploadID = 11,
      Title = "090216ba8014f3be",
      Extension = "pdf",
      Size = 72284
    )
  )
  json_query <- toJSON(json_query, pretty = TRUE, auto_unbox = TRUE)
  json_query <- gsub("\\.1", "", json_query)
}
test_json_q <- create_object()
jsonlite::validate(test_json_q)

但是这2个JSON对象不相同:

identical(test_json, test_json_q)

我看到的问题是第一个JSON对象在[]内有{},但是我不知道如何克服这个问题。

1 个答案:

答案 0 :(得分:0)

我在这里找到了解决方法:R create JSON in R

所以,答案是:

create_object <- function(){
  json_query <- list(
    PropertyValues = I(list(
      list(PropertyDef = 100,
      TypedValue = list(
        DataType = 9,
        HasValue = FALSE,
        Value = NA,
        Lookup = list(
          Deleted = FALSE,
          DisplayValue = NA,
          Hidden = FALSE,
          Item = 1,
          Version = -1
        ),
        Lookups = NA,
        DisplayValue = NA,
        SortingKey = NA,
        SerializedValue = NA
      )),
      list(PropertyDef = 0,
      TypedValue = list(
        DataType = 1,
        HasValue = FALSE,
        Value = "090216ba8014f3be",
        Lookup = NA,
        Lookups = NA,
        DisplayValue = NA,
        SortingKey = NA,
        SerializedValue = NA
      ))
    )),
    Files = list(I(list(
      UploadID = 13,
      Title = "090216ba8014f3be",
      Extension = "pdf",
      Size = 72284
    )))
  )
  json_query <- jsonlite::toJSON(json_query, auto_unbox = TRUE, pretty = TRUE)
  json_query <- gsub("\\.1", "", json_query)
}