Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json - stringify so that arrays are on one line

Tags:

json

stringify

Is it possible to stringify a JSON object to look like this, with arrays in one line - not indented

{     "Repeat": {         "Name": [["Top_level","All"],[[1,1]]],         "Link": [["Top_level"],[[1,1]]]     },     "Delete": ["Confirm","Cancel"],     "Move": ["Up","Down"],     "Number": ["Ascending","Descending"] } 
like image 535
Chris Glasier Avatar asked Aug 04 '11 07:08

Chris Glasier


People also ask

Does JSON Stringify work on arrays?

The JSON array data type cannot have named keys on an array. When you pass a JavaScript array to JSON. stringify the named properties will be ignored. If you want named properties, use an Object, not an Array.

Can I Stringify array?

Stringify a JavaScript ArrayIt is also possible to stringify JavaScript arrays: Imagine we have this array in JavaScript: const arr = ["John", "Peter", "Sally", "Jane"]; Use the JavaScript function JSON.

How do you store several paragraphs of text as a string in JSON?

structure your data: break the multiline string into an array of strings, and then join them later on. Try hjson tool. It will convert your multiline String in json to proper json-format.

Does JSON Stringify work on nested objects?

stringify does not stringify nested arrays. Bookmark this question. Show activity on this post.


1 Answers

Try this:

var obj = {"Repeat": {"Name":[["Top_level","All"],[[1,1]]],"Link": [["Top_level"],[[1,1]]]},"Delete": ["Confirm","Cancel"],"Move": ["Up","Down"],"Number": ["Ascending","Descending"]};  JSON.stringify(obj,function(k,v){    if(v instanceof Array)       return JSON.stringify(v);    return v; },2); 

Result:

"{   "Repeat": {     "Name": "[[\"Top_level\",\"All\"],[[1,1]]]",     "Link": "[[\"Top_level\"],[[1,1]]]"   },   "Delete": "[\"Confirm\",\"Cancel\"]",   "Move": "[\"Up\",\"Down\"]",   "Number": "[\"Ascending\",\"Descending\"]" }" 
like image 72
ericbowden Avatar answered Sep 23 '22 17:09

ericbowden