如何从JSON响应中获取数据表

时间:2020-09-17 07:53:05

标签: r json dataframe

我正在使用API​​来获取数据。响应为JSON格式。到目前为止,我已经使用了以下步骤。

s2 <- GET("https://api2.elasticgrid.com/api/v1/analytics/vendor/partnerengagement/advanced/all") 

char <- rawToChar(s2$content)

我得到的输出为

char 

[1] "{\n\t\"data\":  [\n\t\t{\"Entity Type\":\"transfer_fund\",\"Entity ID\":\"136023000000199105\",\"Reference Number\":\"\",\"Transaction Number\":\"6\",\"Transaction Amount (BCY)\":\"INR 2,600.00\",\"Account ID\":\"136023000000000361\",\"Debit or Credit\":\"debit\",\"Transaction Date\":\"15 Apr 2016\",\"Currency Code\":\"INR\",\"Tax ID\":\"\",\"Taxable Amount (BCY)\":\"INR 0.00\",\"Accrual Transaction ID\":\"136023000000199113\",\"Transaction Amount\":\"-INR 2,600.00\",\"Customer ID\":\"\",\"Vendor ID\":\"\",\"Transaction Amount (FCY)\":\"INR 2,600.00\",\"Taxable Amount (FCY)\":\"INR 0.00\",\"Last Modified Time\":\"2016-05-17 09:38:27\",\"Transaction ID\":\"136023000000199107\",\"Reference No.\":\"\",\"Project ID\":\"\",\"Account Name\":\"Petty Cash\",\"Account Type\":\"Cash\"}.....

如何将其转换为数据表?

谢谢。

1 个答案:

答案 0 :(得分:2)

我无法访问地址,但要读取JSON到R对象,请使用fromJSON()包中的jsonlite函数:

data <- jsonlite::fromJSON(char)

更新: 该文件存在一些特殊字符的问题。您需要先替换它们:

char <- gsub("\t", " ", char, fixed = T) # ideally we need to replace tab characters in strings to '\t' but it's not possible to do that since it'd replace tab characters outside strings as well and cause problems
char <- gsub("\\'", "\'", char, fixed = T)
data <- jsonlite::fromJSON(char)$data