Search code examples
javascriptnode.jsjsonjsonlines

How to manipulate jsonl objects


Given an API that returns a jsonl, how can I manipulate the data that I obtain?

What if the API gives me data like this:

{"plate": "pizza", "quantity": 3}
{"plate": "pasta", "quantity": 2}
  1. In javascript the object retrieved what type will have?
  2. If I want to add a new object, to have a result like:
{"plate": "pizza", "quantity": 3}
{"plate": "pasta", "quantity": 2}
{"plate": "hotdog", "quantity": 7}

How can I do that maintaining the type .jsonl and not creating and array?

Thanks a lot for the help


Solution

  • According to jsonlines.org, each line in a jsonl file is a valid JSON value.

    Thus, the approach would seem to be:

    1. split the file into lines.
    2. parse each line separately as JSON.

    Something like this:

    const lines = data.split(/\n/);
    lines.forEach(line => {
      const object = JSON.parse(line);
      // Do something with object.
    });