首页 > 解决方案 > 将字符串转换为 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.

谁能告诉我我在哪里犯错?我需要做哪些修改?提前谢谢了!

标签: r

解决方案


这对我来说看起来不像普通的 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"

推荐阅读