简体   繁体   中英

convert JSON object to a string

Hi i want to convert the json object to a string with special characters escaped.

following is the example

{
"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"
    }
]
}

above object to

{\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}

can anybody please help me here ?

Thanks in advance.

Hi,

My JSON contains some added plugins because of which the stringify function is not working. for example

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

This is something where the things are not working for me , and i hope somebody can help me out here.

Thanks in advance.

I'm not sure of why you might want this. Is the goal to build a string literal that you could write in a program ?

But, anyway, this seems to do it :

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

Note that what you have to start with isn't a "JSON object" (which means nothing as JSON is a data-exchange format) but a plain javascript object.

jsbin example

Using org.json library:

here is one sample code.

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

or

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM