Search code examples
javascriptjsongmail-api

How to reference a property of JSON


I have the following results being returned by the Gmail API. What is the best way to use the JSON object?

{"result":{"messages":[{"id":"15d862a00074a324","threadId":"15d862a00074a324"},{"id":"15d8628752224d1b","threadId":"15d8628752224d1b"},{"id":"15d8231cfbca0608","threadId":"15d8231cfbca0608"},{"id":"15d812cb47b30f24","threadId":"15d812cb47b30f24"},{"id":"15d5e26548a7fe5b","threadId":"15d5e26548a7fe5b"}],"resultSizeEstimate":5},"body":"{\n \"messages\": [\n  {\n   \"id\": \"15d862a00074a324\",\n   \"threadId\": \"15d862a00074a324\"\n  },\n  {\n   \"id\": \"15d8628752224d1b\",\n   \"threadId\": \"15d8628752224d1b\"\n  },\n  {\n   \"id\": \"15d8231cfbca0608\",\n   \"threadId\": \"15d8231cfbca0608\"\n  },\n  {\n   \"id\": \"15d812cb47b30f24\",\n   \"threadId\": \"15d812cb47b30f24\"\n  },\n  {\n   \"id\": \"15d5e26548a7fe5b\",\n   \"threadId\": \"15d5e26548a7fe5b\"\n  }\n ],\n \"resultSizeEstimate\": 5\n}\n"}

I'm new to JSON objects, but I am familiar with PHP objects and arrays. I will be wanting to reference the resultSizeEstimate and iterate over the id's.

I was trying JSON.stringify(response.resultSizeEstimate);, but without any luck. What is the way for working with JSON objects? I can’t seem to find any standard way.

This is the function I am creating. appendpre just outputs to an element...

  function getUnread() {
    gapi.client.gmail.users.messages.list({
      'userId': 'me',
      'q': 'is:unread in:inbox',
    }).then(function(response) {
      var unread = response;
      appendPre(JSON.stringify(response)); // Outputs JSON with string chars \n's
      console.log(JSON.parse(response)); // Errors as invalid JSON

    });
  }

Here is the working function for reference...

  function getUnread() {
    gapi.client.gmail.users.messages.list({
      'userId': 'me',
      'q': 'is:unread in:inbox',
    }).then(function(response) {
      var unread = JSON.parse(JSON.stringify( response ));
      appendPre(unread.result.resultSizeEstimate);
    });
  }

Solution

  • You should use the JSON.parse function. It accepts JSON content, and returns an object.

    let json = `
    {
      "result": {
        "messages": [
          {"id":"15d862a00074a324","threadId":"15d862a00074a324"},
          {"id":"15d8628752224d1b","threadId":"15d8628752224d1b"},
          {"id":"15d8231cfbca0608","threadId":"15d8231cfbca0608"},
          {"id":"15d812cb47b30f24","threadId":"15d812cb47b30f24"},
          {"id":"15d5e26548a7fe5b","threadId":"15d5e26548a7fe5b"}
        ],
        "resultSizeEstimate": 5
      }
    }`;
    
    let obj = JSON.parse(json);
    console.log('resultSizeEstimate', obj.result.resultSizeEstimate);
    console.log('message ids', obj.result.messages.map(msg => msg.id));