Fix up the end of a partial JSON string to create valid JSON.
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!
With NPM:
npm install untruncate-json
With Yarn:
yarn add untruncate-json
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.
untruncateJson
does not attempt to validate the input JSON. Therefore if
the input JSON is not the prefix of valid JSON, then the output will not be
valid JSON and will fail if you try to parse it.t
, then untruncateJson
will
assume that it was the start of the token true
.Copyright © 2019 David Philipson