瀏覽代碼

make json bidirectional (based on #572)

Evan You 11 年之前
父節點
當前提交
bdb4dc4c13
共有 2 個文件被更改,包括 26 次插入4 次删除
  1. 13 2
      src/filters/index.js
  2. 13 2
      test/unit/specs/filters_spec.js

+ 13 - 2
src/filters/index.js

@@ -6,8 +6,19 @@ var _ = require('../util')
  * @param {Number} indent
  */
 
-exports.json = function (value, indent) {
-  return JSON.stringify(value, null, Number(indent) || 2)
+exports.json = {
+  read: function (value, indent) {
+    return typeof value === 'string'
+      ? value
+      : JSON.stringify(value, null, Number(indent) || 2)
+  },
+  write: function (value) {
+    try {
+      return JSON.parse(value)
+    } catch (e) {
+      return value
+    }
+  }
 }
 
 /**

+ 13 - 2
test/unit/specs/filters_spec.js

@@ -3,11 +3,22 @@ var filters = require('../../../src/filters')
 
 describe('Filters', function () {
 
-  it('json', function () {
-    var filter = filters.json
+  it('json read', function () {
+    var filter = filters.json.read
     var obj = {a:{b:2}}
     expect(filter(obj)).toBe(JSON.stringify(obj, null, 2))
     expect(filter(obj, 4)).toBe(JSON.stringify(obj, null, 4))
+    // plain string
+    expect(filter('1234')).toBe('1234')
+  })
+
+  it('json write', function () {
+    var filter = filters.json.write
+    var obj = '{"a":{"b":2}}'
+    expect(JSON.stringify(filter(obj))).toBe(obj)
+    // error condition
+    var invalidJSON = '{"a":}'
+    expect(filter(invalidJSON)).toBe(invalidJSON)
   })
   
   it('capitalize', function () {