2013-03-06 205 views
2

嗨,我想将json对象转换为具有特殊字符的字符串转义。将JSON对象转换为字符串

下面的例子

{ 
"xtype": "window", 
"height": 250, 
"width": 400, 
"bodyPadding": "20 0 0 20", 
"title": "Configuration", 
"modal": true, 
"items": [ 
    { 
     "xtype": "textfield", 
     "fieldLabel": "Deploy Path" 
    }, 
    { 
     "xtype": "textfield", 
     "fieldLabel": "Save Path" 
    }, 
    { 
     "xtype": "button", 
     "margin": "20 0 0 100", 
     "text": "Save" 
    } 
] 
} 

上述对象

{\n \"xtype\": \"window\",\n \"height\": 250,\n \"width\": 400,\n \"bodyPadding\": \"20 0 0 20\",\n \"title\": \"Configuration\",\n \"modal\": true,\n \"items\": [\n  {\n   \"xtype\": \"textfield\",\n   \"fieldLabel\": \"Deploy Path\"\n  },\n  {\n   \"xtype\": \"textfield\",\n   \"fieldLabel\": \"Save Path\"\n  },\n  {\n   \"xtype\": \"button\",\n   \"margin\": \"20 0 0 100\",\n   \"text\": \"Save\"\n  }\n ]\n} 

任何人可以帮我吗?

在此先感谢。

嗨,

我的JSON包含一些额外的插件,因为它的字符串化功能无法正常工作。例如

plugins: [ 
Ext.create('Ext.grid.plugin.CellEditing', { 
ptype: 'cellediting' 
}) 
] 

这是事情没有为我工作的地方,我希望有人能帮助我在这里。

在此先感谢。

+0

你尝试过什么? - > JSON.parse ??? - > https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse – GreenGuerilla 2013-03-06 14:04:23

+4

这不是同一个问题。 OP要求转义某些字符。停止投票结束这个问题。 – 2013-03-06 14:06:44

+1

另外'JSON.parse'是完全错误的,'stringify'是正确的。 – Christoph 2013-03-06 14:12:58

回答

7

我不确定你为什么要这样做。目标是建立一个可以在程序中编写的字符串文字吗?

但是,不管怎样,这似乎做到这一点:

var str = JSON.stringify(obj, null, '\n') 
      .replace(/"/g, '\\"') 
      .replace(/\n/g, ' ') 
      .replace(/(?:[ ]{4}((?:[ ]{4})*))/g, '\\n$1'); 

请注意,你必须开始与是不是“JSON对象”(这意味着什么作为JSON是一种数据交换格式)但一个普通的JavaScript对象。

jsbin example

+1

感谢您澄清“JSON对象”流行的误解...... – Christoph 2013-03-06 14:10:37

+1

我已经改变了解决方案,我相信,更接近OP后。希望你不介意。 – 2013-03-06 14:36:41

+1

@fireeyedboy不,我真的不介意。你可能是对的(很难确定OP没有回应)。 – 2013-03-06 14:37:29

0

使用org.json库:

这里是一个示例代码。

JSONObject jsonObj = new JSONObject("{\"phonetype\":\"N95\",\"cat\":\"WP\"}"); 

var j={"name":"phonetype"}; 
JSON.stringify(j); // '{"name":"phonetype"}'