无法在用户脚本中解析 json
Can't parse json in userscript
我是 JavaScript 的新手,我可以说 bash 脚本比这更容易。我想从 url 获取 json 文件,然后解析以获取 ID 列表。我在 android 上使用移动 firefox。在 bash 脚本中你写 curl "your url" | jq '.id'
。然后你从 json 文件中得到 id。这是我的代码
// ==UserScript==
// @name qwerty
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http*://*
// @grant GM_xmlhttpRequest
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @copyright 2012+, You
// ==/UserScript==
//Test if script not work
var b = "asdf"
alert(b)
alert(11);
//Script gets file from json url
GM_xmlhttpRequest({
method: "GET",
url: "your url to json",
onload: processJSON_Response
});
//Site response test
function processJSON_Response(rspObj) {
if (rspObj.status != 200 && rspObj.status != 304) {
reportAJAX_Error(rspObj);
return;
}
//Alert to check response is correct or no
alert(rspObj.response)
var a = rspObj.response
//This code not work. It's json parsing
var id = a.id
//Alert id list of json
alert(id)
}
测试json文件
{"updated_at":"2020-04-27T18:52:13.107-04:00","id":[637,677,5765,202]}
您需要致电JSON.parse
:
var a= JSON.parse(rspObj.response);
我是 JavaScript 的新手,我可以说 bash 脚本比这更容易。我想从 url 获取 json 文件,然后解析以获取 ID 列表。我在 android 上使用移动 firefox。在 bash 脚本中你写 curl "your url" | jq '.id'
。然后你从 json 文件中得到 id。这是我的代码
// ==UserScript==
// @name qwerty
// @namespace http://use.i.E.your.homepage/
// @version 0.1
// @description enter something useful
// @match http*://*
// @grant GM_xmlhttpRequest
// @require http://code.jquery.com/jquery-3.4.1.min.js
// @copyright 2012+, You
// ==/UserScript==
//Test if script not work
var b = "asdf"
alert(b)
alert(11);
//Script gets file from json url
GM_xmlhttpRequest({
method: "GET",
url: "your url to json",
onload: processJSON_Response
});
//Site response test
function processJSON_Response(rspObj) {
if (rspObj.status != 200 && rspObj.status != 304) {
reportAJAX_Error(rspObj);
return;
}
//Alert to check response is correct or no
alert(rspObj.response)
var a = rspObj.response
//This code not work. It's json parsing
var id = a.id
//Alert id list of json
alert(id)
}
测试json文件
{"updated_at":"2020-04-27T18:52:13.107-04:00","id":[637,677,5765,202]}
您需要致电JSON.parse
:
var a= JSON.parse(rspObj.response);