R convert dataframe to JSON

后端 未结 4 1944
我在风中等你
我在风中等你 2020-11-28 09:24

I have a dataframe that I\'d like to convert to json format:

my data frame called res1:

library(rjson)

structure(list(id = c(1, 2, 3, 4, 5), value =         


        
相关标签:
4条回答
  • 2020-11-28 09:46

    You can also use library(jsonify)

    jsonify::to_json( res1 )
    # [{"id":1.0,"value":"server1"},{"id":2.0,"value":"server2"},{"id":3.0,"value":"server3"},{"id":4.0,"value":"server4"},{"id":5.0,"value":"server5"}]
    
    0 讨论(0)
  • 2020-11-28 09:50

    How about

    library(rjson)
    x <- toJSON(unname(split(res1, 1:nrow(res1))))
    cat(x)
    # [{"id":1,"value":"server1"},{"id":2,"value":"server2"},
    # {"id":3,"value":"server3"},{"id":4,"value":"server4"},
    # {"id":5,"value":"server5"}]
    

    By using split() we are essentially breaking up the large data.frame into a separate data.frame for each row. And by removing the names from the resulting list, the toJSON function wraps the results in an array rather than a named object.

    0 讨论(0)
  • 2020-11-28 09:54

    The jsonlite package exists to address exactly this problem: "A practical and consistent mapping between JSON data and R objects."

    Its toJSON function provides this desired result with the default options:

    library(jsonlite)
    x <- toJSON(res1)
    cat(x)
    
    ## [{"id":1,"value":"server1"},{"id":2,"value":"server2"},
    ## {"id":3,"value":"server3"},{"id":4,"value":"server4"},
    ## {"id":5,"value":"server5"}]
    
    0 讨论(0)
  • 2020-11-28 09:54

    Now you can easily just call jsonlite::write_json() directly on the dataframe.

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