简体   繁体   English

在R中将多列转换为Json数组?

[英]Turn Multiple Column into Json Array in R?

Say I have the mtcars dataset, and I wanted to take three columns and turn them into a JSON array. 假设我有mtcars数据集,我想取三列并将它们转换为JSON数组。 How do I convert this to a json array and is that possible to pass them into a POSTGRESQL database? 如何将其转换为json数组,是否可以将它们传递到POSTGRESQL数据库?

library(jsonlite)
df <- mtcars
attach(mtcars)
json.column <- cbind(mpg,cyl,disp) 

Do I use toJSON() ? 我使用toJSON()吗?

mtcars.json <- toJSON(json.column)

https://cran.r-project.org/web/packages/jsonlite/vignettes/json-aaquickstart.html https://cran.r-project.org/web/packages/jsonlite/vignettes/json-aaquickstart.html

Array of objects [{"name":"Erik", "age":43}, {"name":"Anna", "age":32}] Data Frame simplifyDataFrame 对象数组[{“name”:“Erik”,“age”:43},{“name”:“Anna”,“age”:32}]数据框simplifyDataFrame

Keep your data as a data.frame, not a matrix. 将数据保存为data.frame,而不是矩阵。 Use 采用

json.column <- data.frame(mpg,cyl,disp)
toJSON(json.column)
# [{"mpg":21,"cyl":6,"disp":160},{"mpg":21,"cyl":6,"disp":160}, ...

Also, you should avoid the use of attach() . 此外,您应该避免使用attach() It can cause lots of problems if you forget detach() . 如果忘记detach()它可能会导致很多问题。 Plus you can use with() often to avoid it 另外,您可以经常使用with()来避免它

json.column <- with(mtcars, data.frame(mpg,cyl,disp))

(For starters, never use attach ! It's dangerous! Use with instead, typically.) (对于初学者,从来不使用attach !这是危险的!用with ,而不是通常)。

There are a bunch of ways to do it. 有很多方法可以做到这一点。 Here's how to create the values using dplyr: 以下是使用dplyr创建值的方法:

qq <- rowwise(mtcars) %>% 
    mutate(newcol=as.character(jsonlite::toJSON(list(mpg=mpg, cyl=cyl, disp=disp))))
> qq$newcol
 [1] "{\"mpg\":[21],\"cyl\":[6],\"disp\":[160]}"     "{\"mpg\":[21],\"cyl\":[6],\"disp\":[160]}"    
 [3] "{\"mpg\":[22.8],\"cyl\":[4],\"disp\":[108]}"   "{\"mpg\":[21.4],\"cyl\":[6],\"disp\":[258]}"  
 ...

From there, if your Postgres database is set up with newcol as a JSON type, I think just writing that table as usual should work. 从那里,如果您的Postgres数据库设置为newcol作为JSON类型,我认为只是像往常一样编写该表应该工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM