javascriptjsontypescriptparsing

How to skip certain fields in JSON object when parsing to improve performance?


I am receiving a large stringified JSON object, with several fields, some of which are big. For example, let's say the object is something like:

{
  "somethingHuge": (200 000 character string)
  "relevantField": true
}

I am only interested in relevantField, so to save performance, I don't want to parse somethingHuge, allocate memory to hold that string, etc. Is it possible to skip that field when parsing?

Note: the object's shape is decided by external factors, there's no way to receive just the relevant data.


Solution

  • You could use the reviver argument to avoid the field being stored on your result object. It will still be parsed, but at least it can be thrown away immediately and your resulting object won't need to allocate space for the property.

    const json = "{ \"somethingHuge\": \"(200 000 character string)\", \"relevantField\": true }";
    
    const parsedObject = JSON.parse(json, (key, value) => {
      return key === "somethingHuge" ? undefined : value;
    });
    
    console.log(parsedObject);

    Not sure how much of a performance benefit this would be since I haven't measured it but without doing something like removing it form the JSON string parsing (or using a custom JSON library) I don't see any other way around it.