Skip to content

Commit

Permalink
fix embed_json for multiline strings
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanatkn committed Jul 15, 2024
1 parent 014b508 commit dac5852
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/slimy-tigers-lay.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ryanatkn/belt': patch
---

fix `embed_json` for multiline strings
9 changes: 5 additions & 4 deletions src/lib/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,10 +25,11 @@ test('embed_json', () => {
assert.is(embed_json("hello'world"), `JSON.parse('"hello\\'world"')`);
assert.is(embed_json("'hello'w''or'''ld'"), `JSON.parse('"\\'hello\\'w\\'\\'or\\'\\'\\'ld\\'"')`);
assert.is(
embed_json(`hello
world
newline`),
`JSON.parse('"hello\\\nworld\\\n\\tnewline"')`,
embed_json({a: 1, b: 2}, (d) => JSON.stringify(d, null, '\t')),
`JSON.parse('{\\
"a": 1,\\
"b": 2\\
}')`,
);
});

Expand Down
12 changes: 11 additions & 1 deletion src/lib/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,14 @@ export const canonicalize = <T extends Json>(value: T): T => {
* Useful for optimizing JSON in JS because it parses faster.
*/
export const embed_json = <T>(data: T, stringify: (data: T) => string = JSON.stringify): string =>
`JSON.parse('${stringify(data).replaceAll("'", "\\'").replaceAll('\\n', '\\\n')}')`;
`JSON.parse('${stringify(data).replaceAll("'", "\\'").replaceAll('\n', '\\\n')}')`;

// const jsonString = stringify(data)
// .replace(/\\/g, '\\\\')
// .replace(/'/g, "\\'")
// .replace(/\n/g, '\\n')
// .replace(/\r/g, '\\r')
// .replace(/\t/g, '\\t');

// return `JSON.parse('${jsonString}')`;
// };

0 comments on commit dac5852

Please sign in to comment.