Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

convert JSON object to a string

Tags:

javascript

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.

like image 226
Deepak Patil Avatar asked Feb 19 '26 21:02

Deepak Patil


1 Answers

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

like image 73
Denys Séguret Avatar answered Feb 22 '26 11:02

Denys Séguret