Search code examples
node.jsjsonstream-json

Accessing nested values with stream-json


I'm trying to access the value "RESPONSE" from the following JSON using the node library stream-json. I'm having difficulty getting it, because when I stream, it prints every level of the json. How can I access it? This JSON is coming in from a stream, that's why I'm using that library.

{
  "outputs": [
    {
      "structVal": {
        "candidates": {
          "listVal": [
            {
              "structVal": {
                "content": {
                  "stringVal": [
            RESPONSE
                  ]
                },
                "author": {
                  "stringVal": [
                    "1"
                  ]
                }
              }
            }
          ]
        },
        "citationMetadata": {
          "listVal": [
            {
              "structVal": {
                "citations": {}
              }
            }
          ]
        },
        "safetyAttributes": {
          "listVal": [
            {
              "structVal": {
                "categories": {},
                "blocked": {
                  "boolVal": [
                    false
                  ]
                },
                "scores": {}
              }
            }
          ]
        }
      }
    }
  ]
}

When I do

stream.on('data', (parsedData) => {
   console.log(parsedData);
});

I get something like:


{ name: 'startArray' }
{ name: 'startObject' }
{ name: 'startKey' }
{ name: 'stringChunk', value: 'outputs' }
{ name: 'endKey' }
{ name: 'keyValue', value: 'outputs' }
{ name: 'startArray' }
{ name: 'startObject' }

Solution

  • So it turns out I needed to add StreamArray() to my pipeline and remove the filter (as it was filtering out everything I needed) and was able to access the json as normal.