Search code examples
jqueryjsonuserscripts

Can't parse json in userscript


I am newbie in JavaScripts and I can say bash script easier than this. I want get json file from url then parse to get id list. I use mobile firefox on android. In bash script you write curl "your url" | jq '.id' . Then you get id from json file. Here is my code

// ==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)
}

Test json file

{"updated_at":"2020-04-27T18:52:13.107-04:00","id":[637,677,5765,202]}

Solution

  • You need to call JSON.parse:

    var a= JSON.parse(rspObj.response);