r - 将字符串转换为 json 字符串并在 R 中解析
问题描述
我有一个列作为 json 字符串的数据:
reservation reasons
1592 [{"name"=>"jorge", "value"=>"MX"}, {"name"=>"Billing phone number", "value"=>"1123"}, {"name"=>"BillingCountry", "value"=>"USA"}]
1597 [{"name"=>"BillingAddress_Country", "value"=>"IN"}, {"name"=>"Billing phone number country code", "value"=>"IN"}, {"name"=>"Latest amount", "value"=>"583000000"}]
我想按如下方式解析列:
reservation name value
1592 jorge mx
1592 Billing phone number 1123
1592 BillingCountry USA
1597 BillingAddress_Country IN
1597 Billing phone number country code IN
1597 Latest amount 583000000
我在 R 中使用 jsonlite。我的代码中出现以下错误:
data<-read.csv("data.csv")
json<-data$reasons
mydf <- fromJSON(json)
Error: Argument 'txt' must be a JSON string, URL or file.
谁能告诉我我在哪里犯错?我需要做哪些修改?提前谢谢了!
解决方案
这对我来说看起来不像普通的 JSON(或者fromJSON
,这让我感觉好一点)。也许这是它的一些特殊情况或其他东西(?)。更新: @camille 将其识别为 Ruby Hash。
无论如何,我们可以修复它:
reasons <- '{"name"=>"jorge", "value"=>"MX"}, {"name"=>"Billing phone number", "value"=>"1123"}, {"name"=>"BillingCountry", "value"=>"USA"}'
reasons <- gsub("=>", ":", reasons)
reasons <- gsub("[{}]", "", reasons)
reasons <- paste0("{",reasons,"}")
fromJSON(reasons)
$`name` [1] "jorge" $value [1] "MX" $name [1] "Billing phone number" $value [1] "1123" $name [1] "BillingCountry" $value [1] "USA"
推荐阅读
- angular - Angular *ngFor 仅显示数组的一部分
- php - 在 cakephp 视图的 html 表格行中创建表单
- php - 当我在 AWS 中从本地 Homestead 更改为 prod 时,Laravel 引发 SQLite 错误
- java - 多线程异常处理免费资源
- findbugs - 必须为非空,但仅在使用 lambda 时标记为可为空
- java - mongodb聚合多个项目操作
- angular - Angular - TransferState - 页面加载两次(闪烁)
- visual-studio - VS 2017 删除我身上的文件/文件夹
- javascript - 单击第一个单选按钮后未直接显示 Jquery 数组内容
- c# - 查询以根据时间戳条件提取数据