本文介绍了使用 RJSONIO 解析一行 JSON 对象的文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要的:我想解析一个格式为
{"business_id": "rncjoVoEFUJGCUoC1JgnUA", "full_address": "8466 W Peoria Ave\nSte 6\nPeoria, AZ 85345", "open": true, "categories": ["Accountants", "Professional Services", "Tax Services", "Financial Services"], "city": "Peoria", "review_count": 3, "name": "Peoria Income Tax Service", "neighborhoods": [], "longitude": -112.241596, "state": "AZ", "stars": 5.0, "latitude": 33.581867000000003, "type": "business"}
{"business_id": "0FNFSzCFP_rGUoJx8W7tJg", "full_address": "2149 W Wood Dr\nPhoenix, AZ 85029", "open": true, "categories": ["Sporting Goods", "Bikes", "Shopping"], "city": "Phoenix", "review_count": 5, "name": "Bike Doctor", "neighborhoods": [], "longitude": -112.10593299999999, "state": "AZ", "stars": 5.0, "latitude": 33.604053999999998, "type": "business"}
其中每一行都是一个单独的 json 对象.我希望解析后的表单是 RPart 可以作为参数的类型.
where every line is an individual json object. I would like the parsed form to be of a type which RPart can take as an argument.
如果我遍历每一行,我可以让它工作,但根据这个 SO 答案,R 更喜欢使用 apply 函数,而不是单独遍历每一行.
I can get this working if I loop through every line but according to this SO answer it's more R like to use the apply function and not by looping through each line individually.
问题:当我运行代码时出现此错误
Problem: When I run my code I'm getting this error
Error in apply(yelp_df, 1, fromJSON) : dim(X) must have a positive length
我的代码
#!/usr/bin/Rscript
require(graphics)
require(RJSONIO)
con <- file("yelp_phoenix_academic_dataset/yelp_academic_dataset_business.json", "r")
yelp_df <- readLines(con) #rather then guessing what the optimal buffer size of the system is I'll just put everything into memeory
apply(yelp_df, 1, fromJSON)
推荐答案
readLines
正在返回一个字符向量.apply
需要一个数组.使用 lapply
或类似的东西.
readLines
is returning a character vector. apply
expects an array. Use lapply
or something similar.
out <- lapply(readLines("test.txt"), fromJSON)
> head(out[[1]])
$business_id
[1] "rncjoVoEFUJGCUoC1JgnUA"
$full_address
[1] "8466 W Peoria Ave\nSte 6\nPeoria, AZ 85345"
$open
[1] TRUE
$categories
[1] "Accountants" "Professional Services" "Tax Services"
[4] "Financial Services"
$city
[1] "Peoria"
$review_count
[1] 3
这篇关于使用 RJSONIO 解析一行 JSON 对象的文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!