dphilipson / untruncate-json

Fix up the end of a partial JSON string to create valid JSON.
MIT License
40 stars 2 forks source link
json json-string validation

untruncate-json

Fix up the end of a partial JSON string to create valid JSON.

Build Status

Motivation

Have you ever been given a string that started off as valid JSON, but was then truncated to fit under some maximum length? And even though it was invalid JSON because it was cut off in the middle, you still wanted to parse it as JSON anyways so you could extract what information you could from it?

No?

Well if you ever do, then this is the library for you!

Installation

With NPM:

npm install untruncate-json

With Yarn:

yarn add untruncate-json

Usage

Import the untruncateJson function:

import untruncateJson from "untruncate-json";

Call it on a truncated JSON string to get a complete, valid JSON string:

untruncateJson("[1, 2"); // -> "[1, 2]"
untruncateJson('"Hello, Wor'); // -> '"Hello, Wor"'
untruncateJson('{"votes": [true, fa'); // -> '{"votes": [true, false]}'
untruncateJson("123."); // -> "123.0"

untruncateJson will sometimes remove characters as well, if there was no way to infer what value they were starting:

untruncateJson("[1, 2, "); // -> "[1, 2]"
untruncateJson('"abc\\'); // -> '"abc"'
untruncateJson('{"x": 20, "y": '); // -> '{"x": 20}'

Check the test cases for many more examples.

Guarantees

Copyright © 2019 David Philipson