我正在尝试从此回复中提取“错误”部分:
library(RSelenium)
library(XML)
url1 <- "https://flights.makemytrip.com/makemytrip/search/O/O/E/1/0/0/S/V0/DEL_BOM_23-06-2017?contains=false&remove="
# Open Browser (slow at the first start)
rd <- rsDriver(browser = "phantomjs")
# Navigate to page
remDr <- rd[["client"]]
remDr$navigate(url1)
# Download price
elem <- remDr$findElement(using = "css selector", "#min_price")
elemtxt <- elem$getElementAttribute("outerHTML")[[1]]
price <- xpathSApply(htmlParse(elemtxt), "//*[@id='min_price']", xmlValue)
# Format price and output
price <- as.numeric(gsub(",", "", price))
cat("The cheapest flight costs:", price)
坐了几个小时,我试过的每一个谷歌搜索都没有出现帮助。
以下是代码:
{
"sp data": {
"status": {
"connection_status": "successful",
"operation_status": "failed",
"errors": {
"error": [
"email - Field 'email' should be unique"
]
}
}
},
"operation_status": "failed"
}
返回:
$onecoption_res = json_decode(onecoption_api($onecoption_api_data));
$onecoption_error = "";
if(is_object($onecoption_res)){
if($onecoption_res->operation_status == 'failed') {
$onecoption_error = get_object_vars($onecoption_res->{'spot data'}->status->errors->{'error[]'});
}
}
echo $onecoption_error[0];
我错过了什么?
答案 0 :(得分:2)
我认为这应该有效:
echo $onecoption_res->{'sp data'}->status->errors->{error}[0]
我认为你不需要使用get_object_vars,你只是想提取正确的字符串? get_object_vars做了其他事情,请查看此处的文档:http://php.net/manual/en/function.get-object-vars.php
答案 1 :(得分:1)
error
是一个数组属性,因此请error
而不是error[]
:
$onecoption_error = $onecoption_res->{'sp data'}->status->errors->error[0];
答案 2 :(得分:0)
如果需要,你可以在解码json后直接在echo线中访问它:
if (is_string($onecoption_res)) {
$onecoption_res = json_decode($onecoption_res);
}
echo $onecoption_res->sp_data->status->errors->error[0];
答案 3 :(得分:0)
您发布的是JSON字符串,而不是PHP对象。
我建议将它变成这样的数组:
$onecoption_array = json_decode($onecoption_res, true);
然后你可以像这样访问它:
$onecoption_error = $onecoption_array['sp data']['status']['errors']['error'];