Skip to content

Commit

Permalink
add embed_json helper for embedding parsed json strings in js
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanatkn committed Jul 4, 2024
1 parent 173c854 commit f5c02c0
Show file tree
Hide file tree
Showing 4 changed files with 21 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changeset/good-lamps-serve.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@ryanatkn/belt": patch
---

add `embed_json` helper for embedding parsed json strings in js
10 changes: 8 additions & 2 deletions src/lib/json.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
import {test} from 'uvu';
import * as assert from 'uvu/assert';

import {to_json_type} from '$lib/json.js';
import {to_json_type, embed_json} from '$lib/json.js';
import {noop} from '$lib/function.js';

test('basic behavior', () => {
test('to_json_type', () => {
assert.is(to_json_type(''), 'string');
assert.is(to_json_type('1'), 'string');
assert.is(to_json_type(1), 'number');
Expand All @@ -20,4 +20,10 @@ test('basic behavior', () => {
assert.is(to_json_type(Symbol() as any), undefined);
});

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\\'"')`);
});

test.run();
7 changes: 7 additions & 0 deletions src/lib/json.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,10 @@ export const canonicalize = <T extends Json>(value: T): T => {
.map(([k, v]) => [k, canonicalize(v)]),
) as any;
};

/**
* Embeds `data` as a JSON string, escaping single quotes.
* 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("'", "\\'")}')`;
1 change: 1 addition & 0 deletions src/routes/package.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,6 +207,7 @@ export const src_json = {
{name: 'Json_Type', kind: 'type'},
{name: 'to_json_type', kind: 'function'},
{name: 'canonicalize', kind: 'function'},
{name: 'embed_json', kind: 'function'},
],
},
'./log.js': {
Expand Down

0 comments on commit f5c02c0

Please sign in to comment.