Skip to content
Draft
Show file tree
Hide file tree
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
39 changes: 39 additions & 0 deletions lib/types/object.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
const _ = require('lodash');
const normalize = require('../normalize');

const parse = function (string) {
if (string == null) { return string; }

let object;
if (_.isPlainObject(string)) {
object = _.cloneDeep(string);
} else if (_.isString(string)) {
// peek at the string to see if it looks like JSON
if (string.match(/^\s*{/)) {
object = parseObject(string);
}
}

object = object || { valid: false };
if (object.valid == null) { object.valid = true; }
object.raw = string.raw != null ? string.raw : string;
return object;
};

const parseObject = function (string) {
try {
return JSON.parse(string);
} catch (err) {
return { valid: false };
}
};

module.exports = {
parse,
components: [],
maskable: false,
operators: [],
examples: [
'{"property_1":"abc","property_2":"def"}'
].map(parse).map(normalize)
};
2 changes: 1 addition & 1 deletion package-lock.json

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

45 changes: 45 additions & 0 deletions test/object.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
const { assert } = require('chai');
const object = require('../lib/types/object');

describe('Object', function () {
const objects = [
{foo: 'bar'},
'{"foo":"bar"}'
];

for (const val of objects) {
it(`should parse ${typeof val} ${JSON.stringify(val)} as object`, function () {
const parsed = object.parse(val);
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});
}

const invalids = [
' ',
'donkey',
'<foo>bar</foo>'
];

for (const val of invalids) {
it(`should parse ${typeof val} ${JSON.stringify(val)} as invalid`, function () {
const parsed = object.parse(val);
assert.deepEqual(parsed, {valid: false, raw: val});
});
}

it('should ignore whitespace', function () {
const val = ' {"foo":"bar"} ';
const parsed = object.parse(val);
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});

it('should handle parsing a parsed object', function () {
const val = '{"foo":"bar"}';
const parsed = object.parse(object.parse(val));
assert.deepEqual(parsed.valueOf(), {foo: 'bar', valid: true, raw: val});
});

it('should have examples', function () {
assert(object.examples.length);
});
});