Getting JSON key as a String

Hello guys,

I'm trying to compare a String to a big JSON file, where what I want to compare is an object's key, and not value.

A snippet from the JSON file looks like this:

{
"categories": {
    "Advertising": [
      {
        "2leep.com": {  // I want to store this key as a string value
          "http://2leep.com/": [
            "2leep.com"
          ]
        }
      },
      {
        "33Across": {   // I want to store this key as a string value
          "http://33across.com/": [
            "33across.com"
          ]
        }
      },

I'll continuously get a String updated with company names. When I get a new name I want to check if that name is on the list. However since I dont have the url of the companies but only the names, I want to compare the name to object keys. Right now my code looks like this.

    void checkTrackers(){
      String[] nameList = split(org, ' '); 

      JSONObject json = loadJSONObject("data/services.json"); 
      JSONObject values = json.getJSONObject("categories");
      JSONArray trackers = values.getJSONArray("Advertising");

     JSONObject test = trackers.getJSONObject(0); 
     println(test);  
    }

And it outputs the following; {"2leep.com": {"http://2leep.com/": ["2leep.com"]}} How can I get the key (what I marked with bold) name stored as a new String value?

Answers

  • edited April 2017

    @torekndsen --

    Processing's JSONObject has a public method hasKey() (a similar method to the one in StringDict, or HashMap). It isn't documented in the public reference, but it is listed on the JavaDoc:

    hasKey() can be used to implement a simple solution to your problem. The sketch below takes a list of companies ("33Across", "LoremIpsum") and checks against your example JSON. It discovers that "LoremIpsum" is not yet tracked because every call to services.getJSONObject("categories").getJSONArray("Advertising").json.getJSONObject(i).hasKey("LoremIpsum") returns false.

    JSONObject services;
    JSONArray trackers;
    String[] companyNames = {"33Across", "LoremIpsum"};
    
    void setup() {
      services = loadJSONObject("data/services.json"); 
      trackers = services.getJSONObject("categories").getJSONArray("Advertising");
      String[] missing = untracked(trackers, companyNames);
      for(String s : missing){
        println("Missing:", s);
      }
    }
    
    
    String[] untracked(JSONArray json, String[] names) {
      String[] results = {};
      for (String s : names) {
        if (!isTracked(json, s)) {
          results = append(results, s);
        }
      }
      return results;
    }
    
    boolean isTracked(JSONArray json, String name) {
      for (int i=0; i<json.size(); i++) {
        if (json.getJSONObject(i).hasKey(name)) { 
          return true;
        }
      }
      return false;
    }
    
Sign In or Register to comment.