我不确定是否已经问过这个问题,并且对jquery和javascript还不熟悉。但是,我找不到与我的问题有关的任何答案。我正在尝试创建一个apify搜寻器。我需要从以下javascript中提取特定数据
<script type="application/json" class="js-react-on-rails-component">
{
"assetHost": null,
"version": "0.0.4-855-gda76bc6\n",
"availableLocales": [
"de",
"en"
],
.........
"stats": {
"visitors": [
{
"domestic": 600,
"note": "incl. 250 conference participants",
"year": 2017,
"total": 600,
"structure": null,
"latest": true
}
],
"venue": [
{
"total": 376,
"domestic": 376,
"latest": true,
"year": 2017
}
],
"exhibitors": [
{
"total_indirect": 0,
"total": 46,
"domestic": 46,
"latest": true,
"year": 2017
}
]
},
..........
</script>
我需要使用jquery从total
获得以下字段:domestic
和exhibitors
。我尝试了此查询(JSON.parse($('.js-react-on-rails-component').text())).exhibitors.total.text().trim()
,但未返回任何内容。因此,我尝试创建一个变量,并按如下所示对结果进行调用:
function pageFunction(context) {
var $ = context.jQuery;
var exhibitor = JSON.parse($('.js-react-on-rails-component').text());
var total = exhibitor.exhibitors.total;
var domestic = exhibitor.exhibitors.domestic;
if (context.request.label === "START") {
.....
} else {
var result = {
total: total,
domestic: domestic
};
return result;
}
}
但是,此代码也不会返回任何结果。
答案 0 :(得分:1)
自从您开始使用
(JSON.parse($('。js-react-on-rails-component')。text()))。exhibitors.total.text()。trim()
如果您仔细查看json,则json的Exhibitions属性是一个数组,您必须使用 exhibitors [i] .total 和 exhibitors [i] .domestic ,其中i = 0 ... N; 而不是您使用的是Exhibitions.total和Exhibitions.domestic
首先,为了简单起见,请将dom组件带到一个变量中,
var myJson = JSON.parse($('.js-react-on-rails-component').text());
var total = myJson.stats.exhibitors[i].total;
var domestic = myJson.stats.exhibitors[i].domestic;
其中i = 0 ... N;
修改:
请看下面的例子
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<div></div>
<script src="https://code.jquery.com/jquery-3.3.1.js" integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60=" crossorigin="anonymous"></script>
<script type="application/json" id="myjsonscript">
{
"stats": {
"visitors": [
{
"domestic": 600,
"note": "incl. 250 conference participants",
"year": 2017,
"total": 600,
"structure": null,
"latest": true
}
],
"venue": [
{
"total": 376,
"domestic": 376,
"latest": true,
"year": 2017
}
],
"exhibitors": [
{
"total_indirect": 0,
"total": 46,
"domestic": 46,
"latest": true,
"year": 2017
}
]
}
}
</script>
<script id='script' type='text/javascript'>
var myJson = JSON.parse($('#myjsonscript').text());
$('div').html(myJson);
var total = myJson.stats.exhibitors[0].total;
var domestic = myJson.stats.exhibitors[0].domestic;
alert('total:' + total);
alert('domestic: ' + domestic);
</script>
</body>
</html>