2013-03-06 207 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"}'