通过R更改JSON文件中的值

时间:2015-11-27 13:43:20

标签: json r

有没有办法在json文件中更改值或分配新变量,然后以相同的格式返回?

可以使用rjson pachage以data.frame格式在R中获取json文件但是如何在我的更改后将此data.frame转换回json?

修改: 示例代码:

json文件:

{"__v":1,"_id":{"$oid":"559390f6fa76bc94285fa68a"},"accountId":6,"api":false,"countryCode":"no","countryName":"Norway","date":{"$date":"2015-07-01T07:04:22.265Z"},"partnerId":1,"query":{"search":[{"label":"skill","operator":"and","terms":["java"],"type":"required"}]},"terms":[{"$oid":"559390f6fa76bc94285fa68b"}],"time":19,"url":"eyJzZWFyY2giOlt7InRlcm1zIjpbImphdmEiXSwibGFiZWwiOiJza2lsbCIsInR5cGUiOiJyZXF1aXJlZCIsIm9wZXJhdG9yIjoiYW5kIn1dfQ","user":11}
{"__v":1,"_id":{"$oid":"5593910cfa76bc94285fa68d"},"accountId":6,"api":false,"countryCode":"se","countryName":"Sweden","date":{"$date":"2015-07-01T07:04:44.565Z"},"partnerId":1,"query":{"search":[{"label":"company","operator":"or","terms":["microsoft"],"type":"required"},{"label":"country","operator":"or","terms":["se"],"type":"required"}]},"terms":[{"$oid":"5593910cfa76bc94285fa68e"},{"$oid":"5593910cfa76bc94285fa68f"}],"time":98,"url":"eyJzZWFyY2giOlt7InRlcm1zIjpbIm1pY3Jvc29mdCJdLCJsYWJlbCI6ImNvbXBhbnkiLCJ0eXBlIjoicmVxdWlyZWQiLCJvcGVyYXRvciI6Im9yIn0seyJ0ZXJtcyI6WyJzZSJdLCJsYWJlbCI6ImNvdW50cnkiLCJ0eXBlIjoicmVxdWlyZWQiLCJvcGVyYXRvciI6Im9yIn1dfQ","user":13}

代码:

library('rjson')
c <- file(Usersfile,'r')
l <- readLines(c,-1L)
json <- lapply(X=l,fromJSON)
json[[1]]$countryName <- 'Jamaica'
result <- cat(toJSON(json))

输出(是一行,以[开头:

[{"__v":1,"_id":{"$oid":"559390f6fa76bc94285fa68a"},"accountId":6,"api":false,"countryCode":"no","countryName":"Jamaica","date":{"$date":"2015-07-01T07:04:22.265Z"},"partnerId":1,"query":{"search":[{"label":"skill","operator":"and","terms":"java","type":"required"}]},"terms":[{"$oid":"559390f6fa76bc94285fa68b"}],"time":19,"url":"eyJzZWFyY2giOlt7InRlcm1zIjpbImphdmEiXSwibGFiZWwiOiJza2lsbCIsInR5cGUiOiJyZXF1aXJlZCIsIm9wZXJhdG9yIjoiYW5kIn1dfQ","user":11},{"__v":1,"_id":{"$oid":"5593910cfa76bc94285fa68d"},"accountId":6,"api":false,"countryCode":"se","countryName":"Sweden","date":{"$date":"2015-07-01T07:04:44.565Z"},"partnerId":1,"query":{"search":[{"label":"company","operator":"or","terms":"microsoft","type":"required"},{"label":"country","operator":"or","terms":"se","type":"required"}]},"terms":[{"$oid":"5593910cfa76bc94285fa68e"},{"$oid":"5593910cfa76bc94285fa68f"}],"time":98,"url":"eyJzZWFyY2giOlt7InRlcm1zIjpbIm1pY3Jvc29mdCJdLCJsYWJlbCI6ImNvbXBhbnkiLCJ0eXBlIjoicmVxdWlyZWQiLCJvcGVyYXRvciI6Im9yIn0seyJ0ZXJtcyI6WyJzZSJdLCJsYWJlbCI6ImNvdW50cnkiLCJ0eXBlIjoicmVxdWlyZWQiLCJvcGVyYXRvciI6Im9yIn1dfQ","user":13}]

1 个答案:

答案 0 :(得分:0)

convert data frame to json

所以这个问题已经在这里完全回答了^^^

快速摘要::

提供了2个选项。 (A)rjson图书馆 导入库 用于toJSON()方法来创建JSON对象。 (不完全确定unname()函数的作用是什么......:p)。

(B)jsonlite库 导入jsonlite库 只需使用toJSON()方法(与上面相同,但不做任何修改)。 cat()上面的对象。

代码示例位于该链接。希望这有帮助!