Save R JSON object with new lines for each record

前端 未结 3 1610
野趣味
野趣味 2021-01-23 03:54

I\'m trying to save a JSON object where each line is a record. How can I save the JSON object so that the number of lines is equal to the number of records (5 in example below)

相关标签:
3条回答
  • 2021-01-23 04:27

    This might do the trick:

    x2 = strsplit(x, '\\},\\{')
    write.table(x2,"tmp.json")
    
    0 讨论(0)
  • 2021-01-23 04:30

    use jsonlite::stream_out

    df <- mtcars[1:5,]
    jsonlite::stream_out(df, file('tmp.json'))
    

    that gives newline delimited JSON or "ndjson"

    0 讨论(0)
  • 2021-01-23 04:33

    jsonlite::stream_out will only work for flat data.frame objects:

    jsonlite::stream_out (list (iris, mtcars)) # error!
    

    More complex structures can be written with intact line breaks simply using writeLines:

    x <- jsonlite::toJSON (list (iris, mtcars), pretty = TRUE)
    con <- file ("tmp.json")
    writeLines (x, con)
    close (con)
    

    jsonlite::fromJSON will read this straight back.

    0 讨论(0)
提交回复
热议问题