0

So currently, I am getting data via TCP connection and we can tell if a string is a valid JSON object using something like:

let body = '';
client.on('data', (chunk) => {
    body += chunk.toString();
    try {
        let data = JSON.parse(body);
        // data is valid json
    }
    catch (e) {}
});

While this works, can we get all valid Objects in a chunk? Let's say we have

const chunk = // an incomplete object like { "list": [ { "id": 1 }, { "id": 

So in the sample, how can we get a valid object in a string? I'm trying to get { "id": 1 } because it's the only valid object in the string.

1
  • Easy and brittle solution would be to use a regular expression to match non-bracket characters between { and }s, but pretty sure this isn't the sort of thing you should need to do in the first place Commented Jul 3, 2018 at 5:07

1 Answer 1

1

What you need is a streaming JSON parser, such as this one: https://github.com/chrisdickinson/json-parse-stream

As you probably already know, unfinished objects are invalid and somewhat arbitrary. So, you'll have to choose how to handle these situations. That is, only if you're in control of the data and have decided how to handle these situations can you know what to do. The streaming JSON parser will emit objects and such as they're passed in, which should help you get around any incomplete objects.

Sign up to request clarification or add additional context in comments.

1 Comment

This is awesome! Now I can emit objects without waiting for the full data to be done.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.