wobsoriano
wobsoriano

Reputation: 13462

How to get valid objects in a string in JavaScript?

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.

Upvotes: 0

Views: 65

Answers (1)

Brad
Brad

Reputation: 163468

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.

Upvotes: 1

Related Questions