1

Hi I have a set CSV files that I need to import into mongo DB.

my data is already tidy, I want to untidy it to create json object I can import.

For example:

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

I woudl like to create list of json strings like:

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

This was supposed to be a simple problem but it looks that all google results are talking about getting json into a tidy data.frame instead.

1 Answer 1

1

You could do

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
#       }
#     ]
#   } 
Sign up to request clarification or add additional context in comments.

1 Comment

Luke works like charm, thank you. I had a similar idea but you nailed it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.