If your object looks like:

myObject = {"value": " this is a string"};

You don't need to stringify to get the string value, you can use this instead:

myObject.value
Answer from Oleg Gryb on Stack Overflow
🌐
Dirask
dirask.com › snippets › javascript › js+remove+curly+brackets+from+json+stringify
❤ 💻 js remove curly brackets from json stringify - Dirask
JavaScript · [Edit] + 0 · - 0 · Ela-Davey · 663 · Copy · 1 2 3 4 5 6 7 const json = JSON.stringify(user); const text = json.replace(/[{}]/g, ''); // Example output: // // "id":1,"name":"Tom","age":25 · [Edit] + 0 · - 0 · Kevin · 797 · Copy ·
Discussions

Cleanest and easiest way to remove brackets from objects?
Why do you need it? More on reddit.com
🌐 r/Frontend
9
0
May 30, 2020
javascript - Store JSON without brackets and quotes - Stack Overflow
As you can see, I am using stringify to make the JSON more pretty, but it still has all the gross brackets and quotes and spacing as JSON. More on stackoverflow.com
🌐 stackoverflow.com
June 28, 2017
javascript - How do I JSON.stringify( anObject ) without colons, backslashes, curly braces or quotes? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Ask questions, find answers and collaborate at work with Stack Overflow for Teams More on stackoverflow.com
🌐 stackoverflow.com
May 23, 2017
javascript - JSON.stringify(array) surrounded with square brackets - Stack Overflow
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Top answer
1 of 16
179

This simple regular expression solution works to unquote JSON property names in most cases:

const object = { name: 'John Smith' };
const json = JSON.stringify(object);  // {"name":"John Smith"}
console.log(json);
const unquoted = json.replace(/"([^"]+)":/g, '$1:');
console.log(unquoted);  // {name:"John Smith"}

Extreme case:

var json = '{ "name": "J\\":ohn Smith" }'
json.replace(/\\"/g,"\uFFFF");  // U+ FFFF
json = json.replace(/"([^"]+)":/g, '$1:').replace(/\uFFFF/g, '\\\"');
// '{ name: "J\":ohn Smith" }'

Special thanks to Rob W for fixing it.

Limitations

In normal cases the aforementioned regexp will work, but mathematically it is impossible to describe the JSON format with a regular expression such that it will work in every single cases (counting the same number of curly brackets is impossible with regexp.) Therefore, I have create a new function to remove quotes by formally parsing the JSON string via native function and reserialize it:

function stringify(obj_from_json) {
    if (typeof obj_from_json !== "object" || Array.isArray(obj_from_json)){
        // not an object, stringify using native function
        return JSON.stringify(obj_from_json);
    }
    // Implements recursive object serialization according to JSON spec
    // but without quotes around the keys.
    let props = Object
        .keys(obj_from_json)
        .map(key => `{stringify(obj_from_json[key])}`)
        .join(",");
    return `{${props}}`;
}

Example: https://jsfiddle.net/DerekL/mssybp3k/

2 of 16
34

It looks like this is a simple Object toString method that you are looking for.

In Node.js this is solved by using the util object and calling util.inspect(yourObject). This will give you all that you want. follow this link for more options including depth of the application of method. http://nodejs.org/api/util.html#util_util_inspect_object_options

So, what you are looking for is basically an object inspector not a JSON converter. JSON format specifies that all properties must be enclosed in double quotes. Hence there will not be JSON converters to do what you want as that is simply not a JSON format.Specs here: https://developer.mozilla.org/en-US/docs/Using_native_JSON

Object to string or inspection is what you need depending on the language of your server.

🌐
Reddit
reddit.com › r/frontend › cleanest and easiest way to remove brackets from objects?
r/Frontend on Reddit: Cleanest and easiest way to remove brackets from objects?
May 30, 2020 -

Suppose that I have something like '{ last: "Capulet" }'.

How do I turn it into: last: "Capulet"

What would be a consistent way to do this?

For example, in some cases I'd want to turn something like '{ "apple": 1 }' into "apple": 1

Notice how the quotes change places between the example just above and the one in the second sentence?

Top answer
1 of 2
2

The data just needs a bit of massaging

var data = {
    "question1": {
        "Reliable": true,
        "Knowledgeable": false,
        "Helpful": true,
        "Courteous": true
    },
    "question2": {
        "checked": "Extremely Well"
    },
    "question3": {
        "checked": "Extremely Well"
    },
    "question4": {
        "checked": 3
    },
    "fullName": "Test",
    "address": "Test",
    "city": "Test",
    "state": "Test",
    "zip": "321",
    "areaCode": "321",
    "phone": 1234567896,
    "call": true,
    "lifeInsurance": "Yes",
    "brokerage": "Yes",
    "bankName": "Regions"
};

var result = Object.entries(data).reduce((result, [key, value]) => {
    key = key.replace(/([A-Z]|\d+)/g, ' $1').replace(/^(.)/, (unused, p1) => p1.toUpperCase());
    if (!['string', 'number', 'boolean'].includes(typeof value)) {
        value = Object.entries(value).map(([key, value]) => (typeof value == 'boolean') ? (value ? key : undefined) : value).filter(v => v !== undefined).join(',');
    }
    result.push(`${key}: ${value}`);
    return result;
}, []);
console.log(result.join('\n'));
Run code snippetEdit code snippet Hide Results Copy to answer Expand

Note: I changed one of the true to false to check the logic

Tested in node 8.1.2

2 of 2
0

An even easier answer might be parsing the JSON then dumping it as YAML:

---
question1:
  Reliable: true
  Knowledgeable: true
  Helpful: true
  Courteous: true
question2:
  checked: Extremely Well
question3:
  checked: Extremely Well
question4:
  checked: 3
fullName: Test
address: Test
city: Test
state: Test
zip: '321'
areaCode: '321'
phone: 1234567896
call: true
lifeInsurance: 'Yes'
brokerage: 'Yes'
bankName: Regions

There are several YAML libraries for Node.js, and I don't remember which I like, but I want to say I have had pretty good luck with js-yaml.

🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › stringify
JSON.stringify() - JavaScript - MDN Web Docs
The JSON.stringify() static method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Find elsewhere
🌐
Mozilla Bugzilla
bugzilla.mozilla.org › show_bug.cgi
554333 - JSON.stringify returns an empty set of square brackets when an associative array is passed.
September 21, 2022 - Matthew, note that if by "associative array" you basically mean "a set of keys and values", then a JS Object is more or less what you want (and will stringify as you seem to expect). Thank you, Boris. Object are in fact working perfectly for me now that I know that's how I have to do it. I was doing everything server side with associative arrays, so I wanted to do the same in my javascript to be symetrical.
🌐
Reddit
reddit.com › r/learnprogramming › [php / javascript] how can i avoid removing square brackets from arrays in php when using json_encode
r/learnprogramming on Reddit: [PHP / JavaScript] How can I avoid removing square brackets from arrays in PHP when using json_encode
June 16, 2014 -

So I have an array of objects that I converted to JSON using JSON.stringify in JavaScript. I want to save this json to a file using PHP, and I can do this using json_encode in PHP (which I've done), but using this function adds a whole bunch of escape backslashes to the string and removes the square brackets from the json. I want to use this json in another javascript file, but the absence of square brackets makes it extremely difficult to parse properly or use it the object as it originally was. How can I preserve the square brackets?

The relevant code looks like this:

$('#saveHierarchy').on('click', ':button', function() {
	  jsonString = JSON.stringify({adHierarchy:adHierarchy},null,'\t');
  console.log(jsonString);  	
  $.ajax({
    type: 'GET',
    url: '/test/generator/save.php/',
    data: jsonString,
    contentType: 'application/json; charset=utf-8',
    success: function(response) {
      console.log(response);
    },
    error: function(xhr, status) {
  	  console.log(status);
    }
  });
});

And save.php:

<?php
    $fp = fopen("SaveData.json","w");
    fwrite($fp, json_encode($_GET));
    fclose($fp);
?>
🌐
Ionic Framework
forum.ionicframework.com › ionic-v1
How remove curly braces {} from all string of a json - ionic-v1 - Ionic Forum
December 18, 2015 - Hi, i’ve a huge JSON that contains data like this {“caseFolderId”:"{2854EE70-146A-4618-826C-BA33FC807A25}",“caseTaskId”:"{28BE9F56-A7D7-4CA5-B777-A51FF3847236}",“stepName”:“Item details”,“columns”:{“DV_NAMECL_POS_ODA”:“Tieleman Transport BV”,“DV_MATNR_TXZ01_POS_ODA”:“445811 - EUROPRENE SBR 1500 GUC BOX 1110 P150 - 1”,“F_StepName”:“Item details”,“DV_Caseidentifier_for_eni_OdA”:null,“DV_MENGE_MEINS_POS_ODA”:“20.000 - KG”,“DV_PEINH_POS”:“1000 - KG”,“DV_NETPR_WAERS_POS_ODA”:“1.000 - EUR”,“DV_EINDT_...
🌐
Google Developer forums
googlecloudcommunity.com › google cloud › apigee
How to remove square bracket and double quotes from extracted json object - Apigee - Google Developer forums
December 5, 2018 - I have one json array object and i need to extract one particular value out of it, i used JSONPATH to extract it and the output is coming like this [“vIMS”] but i need to remove this square bracket and double quotes and …
Top answer
1 of 2
3

As I said in the comments, you need a for...in [MDN] loop to iterate over the properties of the object and can use recursion to subsequently convert nested objects:

function convert(obj, prefix, result) {
    result = result || {};

    // iterate over all properties
    for (var prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            var value = obj[prop];
            // build the property name for the result object
            // first level is without square brackets
            var name = prefix ? prefix + '[' + prop + ']' : prop;
            if (typeof value !== 'object') {
                // not an object, add value to final result
                result[name] = value;
            }
            else {
                // object, go deeper
                convert(value, name, result);
            }
        }
    }

    return result;
}

// Usage:
var converted_data = convert(data);

DEMO

Still, I would recommend using JSON.

If you want to handle files as well, you might have to add an additional check for File objects. You'd want them raw in the result object:

else if (window.File && value instanceof File) {
    result[name] = value;
}

// and for file lists

else if (window.FileList && value instanceof FileList) {
    for (var i = 0, l = value.length; i < l; i++) {
        result[name + '[' + i + ']'] = value.item(i);
    }
}

It could be that the File (FileList) constructor is named differently in IE, but it should give you a start.

2 of 2
0

Not a big fan of reinventing the wheel, so here is how you could answer your question using object-scan. It's a great tool for data processing - once you wrap your head around it that is.

// const objectScan = require('object-scan');

const convert = (haystack) => objectScan(['**'], {
  filterFn: ({ key, value, isLeaf, context }) => {
    if (isLeaf) {
      const k = key.map((e, idx) => (idx === 0 ? e : `[${e}]`)).join('');
      context[k] = value;
    }
  }
})(haystack, {});

const data = { field: { name: 'Name', surname: 'Surname' }, address: { street: 'Street', number: 0, postcode: 0, geo: { city: 'City', country: 'Country', state: 'State' } }, options: [1, 4, 6, 8, 11] };

console.log(convert(data));
/* =>
  { 'options[4]': 11,
    'options[3]': 8,
    'options[2]': 6,
    'options[1]': 4,
    'options[0]': 1,
    'address[geo][state]': 'State',
    'address[geo][country]': 'Country',
    'address[geo][city]': 'City',
    'address[postcode]': 0,
    'address[number]': 0,
    'address[street]': 'Street',
    'field[surname]': 'Surname',
    'field[name]': 'Name' }
*/
.as-console-wrapper {max-height: 100% !important; top: 0}
<script src="https://bundle.run/object-scan@13.7.1"></script>

Disclaimer: I'm the author of object-scan

🌐
Stack Overflow
stackoverflow.com › questions › 74865744 › json-hijacking-a-string-without-bracket-on-the-outside-is-it-possible
javascript - JSON hijacking a string without bracket on the outside, is it possible? - Stack Overflow
But is just a JSON string '"c29tZXRva2Vu"' created by JSON.stringify('c29tZXRva2Vu') without brackets on the outside exploitable? ... exploitable? means what? It just returns the string. Read the docs on MDN on what it does. developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…