Skip to content

Commit bdb4dc4

Browse files
committed
make json bidirectional (based on vuejs#572)
1 parent 3f0a00b commit bdb4dc4

File tree

2 files changed

+26
-4
lines changed

2 files changed

+26
-4
lines changed

src/filters/index.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,19 @@ var _ = require('../util')
66
* @param {Number} indent
77
*/
88

9-
exports.json = function (value, indent) {
10-
return JSON.stringify(value, null, Number(indent) || 2)
9+
exports.json = {
10+
read: function (value, indent) {
11+
return typeof value === 'string'
12+
? value
13+
: JSON.stringify(value, null, Number(indent) || 2)
14+
},
15+
write: function (value) {
16+
try {
17+
return JSON.parse(value)
18+
} catch (e) {
19+
return value
20+
}
21+
}
1122
}
1223

1324
/**

test/unit/specs/filters_spec.js

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,22 @@ var filters = require('../../../src/filters')
33

44
describe('Filters', function () {
55

6-
it('json', function () {
7-
var filter = filters.json
6+
it('json read', function () {
7+
var filter = filters.json.read
88
var obj = {a:{b:2}}
99
expect(filter(obj)).toBe(JSON.stringify(obj, null, 2))
1010
expect(filter(obj, 4)).toBe(JSON.stringify(obj, null, 4))
11+
// plain string
12+
expect(filter('1234')).toBe('1234')
13+
})
14+
15+
it('json write', function () {
16+
var filter = filters.json.write
17+
var obj = '{"a":{"b":2}}'
18+
expect(JSON.stringify(filter(obj))).toBe(obj)
19+
// error condition
20+
var invalidJSON = '{"a":}'
21+
expect(filter(invalidJSON)).toBe(invalidJSON)
1122
})
1223

1324
it('capitalize', function () {

0 commit comments

Comments
 (0)