Skip to content

feat: new string format "dirty" #760

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 20 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
@@ -641,8 +641,26 @@ const stringify = fastJson({
type: 'object',
properties: {
'code': {
type: 'string',
format 'unsafe'
type: 'string',
format: 'unsafe'
}
}
})
```

<a name="dirty"></a>
#### 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'
}
}
})
16 changes: 16 additions & 0 deletions benchmark/bench.js
Original file line number Diff line number Diff line change
@@ -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: {
2 changes: 2 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -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') {
4 changes: 4 additions & 0 deletions lib/serializer.js
Original file line number Diff line number Diff line change
@@ -129,6 +129,10 @@ module.exports = class Serializer {
return '"' + str + '"'
}

asDirty (str) {
return JSON.stringify(str)
}

getState () {
return this._options
}
6 changes: 6 additions & 0 deletions test/basic.test.js
Original file line number Diff line number Diff line change
@@ -24,6 +24,12 @@ buildTest({
format: 'unsafe'
}, 'hello world')

buildTest({
title: 'string',
type: 'string',
format: 'dirty'
}, 'hello\nworld')

buildTest({
title: 'basic',
type: 'object',