diff --git a/README.md b/README.md index 4bc8f0bd..4e873d83 100644 --- a/README.md +++ b/README.md @@ -641,8 +641,26 @@ const stringify = fastJson({ type: 'object', properties: { 'code': { - type: 'string', - format 'unsafe' + type: 'string', + format: 'unsafe' + } + } +}) +``` + + +#### Dirty 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: 'dirty' } } }) diff --git a/benchmark/bench.js b/benchmark/bench.js index acb87b94..770843fd 100644 --- a/benchmark/bench.js +++ b/benchmark/bench.js @@ -55,6 +55,14 @@ const benchmarks = [ }, input: 'hello world' }, + { + name: 'dirty short string', + schema: { + type: 'string', + format: 'dirty' + }, + input: 'hello\nworld' + }, { name: 'short string with double quote', schema: { @@ -92,6 +100,14 @@ const benchmarks = [ }, input: longString }, + { + name: 'dirty long string', + schema: { + type: 'string', + format: 'dirty' + }, + input: longString + '\n' + }, { name: 'number', schema: { diff --git a/index.js b/index.js index 2390c28a..c0d77ca9 100644 --- a/index.js +++ b/index.js @@ -736,6 +736,8 @@ function buildSingleTypeSerializer (context, location, input) { return `json += serializer.asTime(${input})` } else if (schema.format === 'unsafe') { return `json += serializer.asUnsafeString(${input})` + } else if (schema.format === 'dirty') { + return `json += serializer.asDirty(${input})` } else { return ` if (typeof ${input} !== 'string') { diff --git a/lib/serializer.js b/lib/serializer.js index df81960e..c5950bda 100644 --- a/lib/serializer.js +++ b/lib/serializer.js @@ -129,6 +129,10 @@ module.exports = class Serializer { return '"' + str + '"' } + asDirty (str) { + return JSON.stringify(str) + } + getState () { return this._options } diff --git a/test/basic.test.js b/test/basic.test.js index 754f4489..0c3a6c0b 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: 'dirty' +}, 'hello\nworld') + buildTest({ title: 'basic', type: 'object',