如何从整洁的数据创建json字符串

时间:2017-08-07 21:38:56

标签: r

您好我有一套CSV文件需要导入mongo DB。

我的数据已经很整洁,我想解开它来创建我可以导入的json对象。

例如:

client, receipt, total
1       101      $10
1       102      $11
2       201      $10

我喜欢创建json字符串列表,如:

list:
[1]
{  
   "client":1,
   "receipts":[  
      {  
         "receipt":101,
         "charge":10
      },
      {  
         "receipt":102,
         "charge":11
      }
   ]
}
[2]
{  
   "client":2,
   "receipts":[  
      {  
         "receipt":201,
         "charge":10
      }
   ]
}

这应该是一个简单的问题,但它看起来所有的谷歌搜索结果都在谈论将json变成整洁的data.frame。

1 个答案:

答案 0 :(得分:1)

你可以做到

df<-read.table(header=T, text="client receipt charge
1       101      10
1       102      11
2       201      10")
library(jsonlite)
library(tidyverse)
df %>% 
  nest(-client, .key = receipts) %>% 
  split(.$client) %>% 
  map(~toJSON(unbox(.x), pretty=TRUE)) 
# $`1`
# {
#     "client": 1,
#     "receipts": [
#       {
#         "receipt": 101,
#         "charge": 10
#       },
#       {
#         "receipt": 102,
#         "charge": 11
#       }
#     ]
#   } 
# 
# $`2`
# {
#     "client": 2,
#     "receipts": [
#       {
#         "receipt": 201,
#         "charge": 10
#       }
#     ]
#   }