Skip to content

Commit

Permalink
change embed_json to support multiline strings
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanatkn committed Jul 15, 2024
1 parent abec9f7 commit d173206
Show file tree
Hide file tree
Showing 6 changed files with 18 additions and 7 deletions.
5 changes: 5 additions & 0 deletions .changeset/new-swans-hide.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@ryanatkn/belt': patch
---

change `embed_json` to support multiline strings
8 changes: 4 additions & 4 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
],
"devDependencies": {
"@changesets/changelog-git": "^0.2.0",
"@ryanatkn/eslint-config": "^0.4.1",
"@ryanatkn/eslint-config": "^0.4.2",
"@ryanatkn/fuz": "^0.110.4",
"@ryanatkn/gro": "^0.130.1",
"@ryanatkn/moss": "^0.8.0",
Expand Down
6 changes: 6 additions & 0 deletions src/lib/json.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,12 @@ test('embed_json', () => {
assert.is(embed_json('hello"world'), `JSON.parse('"hello\\"world"')`);
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"')`,
);
});

test.run();
2 changes: 1 addition & 1 deletion src/lib/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ 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("'", "\\'")}')`;
`JSON.parse('${stringify(data).replaceAll("'", "\\'").replaceAll('\\n', '\\\n')}')`;
2 changes: 1 addition & 1 deletion src/routes/package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ export const package_json = {
keywords: ['js', 'typescript', 'utilities', 'web'],
devDependencies: {
'@changesets/changelog-git': '^0.2.0',
'@ryanatkn/eslint-config': '^0.4.1',
'@ryanatkn/eslint-config': '^0.4.2',
'@ryanatkn/fuz': '^0.110.4',
'@ryanatkn/gro': '^0.130.1',
'@ryanatkn/moss': '^0.8.0',
Expand Down

0 comments on commit d173206

Please sign in to comment.