Home > Enterprise >  How can you check if a JSON key with x name exists?
How can you check if a JSON key with x name exists?

Time:09-14

I'm working on a small side project of mine, a TamperMonkey UserScript that automatically skips DJ Khalied music tags on YouTube. I created an API on a free host, but here's what I have so far:

var queryString = window.location.search;
var urlParams = new URLSearchParams(queryString);
var id = urlParams.get('v')
var vidPlayer = document.getElementById("movie_player");
var vidTime = setInterval(vidPlayer.getCurrentTime(), 100);
if(httpGet(checkKhalied   '?id='   id) == 'true'){
    console.log("DJ Khalied Parts In Video! Loading Timestamps...");
    var jsonData = httpGet(checkDisplay   '?id='   id);
    console.log("Loaded Timestamps, Converting JSON to JS Array...");
    jsonData = JSON.parse(jsonData);
    console.log("Converted JSON to JS Array, Watching to Skip DJ Khalied Tags!");
    console.log(jsonData);
    var scanKhalied = setInterval(removeIt, 100);
}else{
    console.log("No DJ Khalied Parts To Skip!");
}


function httpGet(theUrl)
{
    var xmlHttp = new XMLHttpRequest();
    xmlHttp.open( "GET", theUrl, false );
    xmlHttp.send( null );
    return xmlHttp.responseText;
}

function removeIt(){
    if(jsonData[vidTime] !== 'undefined'){
        window.location.href = 'https://www.youtube.com/watch?v='   id   '&t='   jsonData[vidTime];
    }
}

I am aware that checkDisplay and checkKhalied are undefined in the code above, however in my final code this is the website the API is running on (not yet public). httpGet(checkKhalied '?id=' id) returns true or false as a string, and if true httpGet(checkDisplay '?id=' id) should return a JSON array like this example...

{
"1":"10",
"20":"25"
}

Everything is working besides when it is a DJ Khalied video, and I think I did something wrong with the removeIt() function. What it's supposed to do is skip to the value of the key (in the example, the script is supposed to skip from the 1 second point to the 10 second point at first), if a key with the same name as the current video time (vidTime) is sat.

The problem? Everytime I go to a DJ Khalied video I added to the API, it keeps constantly reloading the page over and over. I think there's some loop in my function, but I can't determine what it is or how to break it.

Does anyone know what I'm doing wrong? How can I check if a JSON key with x name exists, since if(jsonData[vidTime] !== 'undefined') is not working?

CodePudding user response:

Use following : JsonData.hasOwnProperty(vidTime) Then it will work.

Refference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty

CodePudding user response:

You have several ways to approach this. For starters if(jsonData[vidTime] !== undefined) or if(!jsonData[vidTime]) could be quick solutions for you depending on the depth of the key as !null -> true and !undefined ->true

A rather 'primitive' method is converting the JSON to a string and then searching for the key using a regEXP

var json = {
  "some_key":"data",
  "key2" :[
    {
      "898":"value"
     }
  ],
  "levels":{
    "level1":{
      "level2":{
        "level3": "data"
        }
       }
   }
}

function hasKey(obj,key){
    var str = JSON.stringify(obj);
    if(str.match(`${key}":`))
        return true;
    return false;
    
}

console.log(hasKey(json,"level3"));
console.log(hasKey(json,"898"));
console.log(hasKey(json,"something"));

For small data sets i would call this method safe enough. You could run into issues however for larger objects as running regular expressions on them can be rather heavy. (couple hundreds lines id say)

Another method you can use is mapping all the keys inside the object recursively and looking trough them. This solution on the other hand could be slow depending on the depth & position of your key.

var json = {
  "some_key":"data",
  "key2" :[
    {
      "898":"value"
     }
  ],
  "levels":{
    "level1":{
      "level2":{
        "level3": "data"
        }
       }
   }
}

function hasKey(obj,property) {
    function getter(o) {
        if (o && typeof o === 'object') {
            return Object.entries(o)
                .map(([key, value]) => key === property ? true : getter(value))
                .filter(Boolean)
                .shift()
        }
    }
    if(getter(obj))
      return true;
    return false;
}

console.log(hasKey(json,"level3"));
console.log(hasKey(json,"898"));
console.log(hasKey(json,"something"));

Currently i do not know of any methods directly implemented in JS

  • Related