2017-09-27 72 views
0

我需要从R(使用jsonlite)中的数据帧中导出json。一切都好,除了一件事。我有一个字符串列在细胞是这样的:将数据帧中的字符串拆分为R中的json数组

"one,two,three" 

所以经过:

sink("out.json") 
cat(toJSON(DF, pretty = TRUE)) 
sink() 

的Json如下:

{..."data" : "one,two,three"...} 

我想数组:

{..."data" : ["one","two","three"]...} 

我试着strsplit覆盖单元格并用单元格替换值json,但它不起作用。

strsplit: 
================== 
Warning message: 
In `[<-.data.frame`(`*tmp*`, 16, 5, value = list(c("one", : 
replacement element 1 has 3 rows to replace 1 rows 

strplit and toJSON for cell: 
================== 
[1] "[\"one\",\"two\",\"three\"]" 

有人可以帮助我吗?谢谢!

回答

0

您可以将列更改为列表而不是字符向量。

library('jsonlite') 
library('tidyverse') 

df <- tribble(
    ~column1, ~data, 
    1,  'one,two,three', 
    2,  'four,five' 
) 

df <- df %>% 
    mutate(data = stringr::str_split(data, ',')) 

toJSON(df, pretty = T) 
# [ 
# { 
#  "a": 1, 
#  "data": ["one", "two", "three"] 
# }, 
# { 
#  "a": 2, 
#  "data": ["four", "five"] 
# } 
# ] 
+0

我不明白“tidyverse”(太大的包装)“tribble”,但我理解你的信息。谢谢。对我来说,工作如下:'df $ data < - as.list(strsplit(df $ data,“,”))' –