diff --git a/README.md b/README.md index 2edd0b18..1f6dd6a4 100644 --- a/README.md +++ b/README.md @@ -646,8 +646,26 @@ const stringify = fastJson({ type: 'object', properties: { 'code': { - type: 'string', - format 'unsafe' + type: 'string', + format: 'unsafe' + } + } +}) +``` + + +#### Extended unicode string +String known to contain non-printable characters or surrogate pairs. + +Example: +```javascript +const stringify = fastJson({ + title: 'Example Schema', + type: 'object', + properties: { + 'code': { + type: 'string', + format: 'extended-unicode' } } }) diff --git a/benchmark/bench.js b/benchmark/bench.js index acb87b94..576b0193 100644 --- a/benchmark/bench.js +++ b/benchmark/bench.js @@ -55,6 +55,14 @@ const benchmarks = [ }, input: 'hello world' }, + { + name: 'extended-unicode short string', + schema: { + type: 'string', + format: 'extended-unicode' + }, + input: 'hello\nworld' + }, { name: 'short string with double quote', schema: { @@ -92,6 +100,14 @@ const benchmarks = [ }, input: longString }, + { + name: 'extended-unicode long string', + schema: { + type: 'string', + format: 'extended-unicode' + }, + input: longString + '\n' + }, { name: 'number', schema: { diff --git a/index.js b/index.js index 019c65fe..2ad1b113 100644 --- a/index.js +++ b/index.js @@ -23,7 +23,8 @@ const { asDateTime, asDate, asTime, - asUnsafeString + asUnsafeString, + asExtendedUnicode } = serializer const asInteger = serializer.asInteger.bind(serializer) @@ -754,6 +755,8 @@ function buildSingleTypeSerializer (context, location, input) { return `json += asTime(${input})` } else if (schema.format === 'unsafe') { return `json += asUnsafeString(${input})` + } else if (schema.format === 'extended-unicode') { + return `json += asExtendedUnicode(${input})` } else { return ` if (typeof ${input} !== 'string') { diff --git a/lib/serializer.js b/lib/serializer.js index 0f4dde76..e9a4a7f1 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -128,6 +128,10 @@ module.exports = class Serializer { return '"' + str + '"' } + asExtendedUnicode (str) { + return JSON.stringify(str) + } + getState () { return this._options } diff --git a/test/basic.test.js b/test/basic.test.js index 754f4489..1bcd91c6 100644 --- a/test/basic.test.js +++ b/test/basic.test.js @@ -24,6 +24,12 @@ buildTest({ format: 'unsafe' }, 'hello world') +buildTest({ + title: 'string', + type: 'string', + format: 'extended-unicode' +}, 'hello\nworld') + buildTest({ title: 'basic', type: 'object',