JSON.stringify(dataArray) will always return square brackets because dataArray is of type array. Instead, you could stringify each element of your array, then join them separated by commas.
dataArray = dataArray.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
Then
["newData",4,2]
becomes
"newData",4,2
Addendum: Please don't try to replace() out the brackets manually because it could be that one day a bracket enters your array in a string. e.g. ["Please see ref[1]",4,2]
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?
JSON.stringify(dataArray) will always return square brackets because dataArray is of type array. Instead, you could stringify each element of your array, then join them separated by commas.
dataArray = dataArray.map(function(e){
return JSON.stringify(e);
});
dataString = dataArray.join(",");
Then
["newData",4,2]
becomes
"newData",4,2
Addendum: Please don't try to replace() out the brackets manually because it could be that one day a bracket enters your array in a string. e.g. ["Please see ref[1]",4,2]
Thanks Drakes and S McCrohan for your answers. I found that .replace(/]|[[]/g, '') appended to JSON.stringify(dataArray)
full line JSON.stringify(dataArray).replace(/]|[[]/g, '')
Print JSON string without quotes and brackets
Store JSON without brackets and quotes
JSON.stringify without quotes on properties?
How to remove square bracket and double quotes from extracted json object
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
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.
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 => `${key}:${stringify(obj_from_json[key])}`)
.join(",");
return `{${props}}`;
}
Example: https://jsfiddle.net/DerekL/mssybp3k/
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.
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);
?>Javascript strings are immutable. When you call blah2.replace, you are not replacing something inside blah2, you are creating a new string. What you probably want is:
blah2 = blah2.replace(/[{}]/g, '');
because i'm going to split it with the comma so it turns into an array, and so when I sort it, I dont want to sort it according to the { and }
zi42 has already given you the correct answer.
But Since you have written as quoted above, looks like what you want is really to sort data and split it in an array; in this case, parsing/splitting it at the comma, etc, is a long way to go about it. Here's another way to think about it:
var data = {foo: 123, bar: <x><y></y></x>, baz: 123};
var key;
var dataSorted = []; // Create an empty array
for (key in data) { // Iterate through each key of the JSON data
dataSorted.push(key);
}
dataSorted.sort();
Now you have the data sorted. When you want to use it, you can use it like this:
for (var i = 0; i < dataSorted.length; i++) {
var key = dataSorted[i];
// Now you do whatever you need with sorted data. eg:
console.log("Key is: " + key + ", value is: " + data[key]);
}
Javascript strings are immutable. When you call blah2.replace, you are not replacing something inside blah2, you are creating a new string. What you probably want is:
blah2 = blah2.replace(/[{}]/g, '');
because i'm going to split it with the comma so it turns into an array, and so when I sort it, I dont want to sort it according to the { and }
zi42 has already given you the correct answer.
But Since you have written as quoted above, looks like what you want is really to sort data and split it in an array; in this case, parsing/splitting it at the comma, etc, is a long way to go about it. Here's another way to think about it:
var data = {foo: 123, bar: <x><y></y></x>, baz: 123};
var key;
var dataSorted = []; // Create an empty array
for (key in data) { // Iterate through each key of the JSON data
dataSorted.push(key);
}
dataSorted.sort();
Now you have the data sorted. When you want to use it, you can use it like this:
for (var i = 0; i < dataSorted.length; i++) {
var key = dataSorted[i];
// Now you do whatever you need with sorted data. eg:
console.log("Key is: " + key + ", value is: " + data[key]);
}
Use this when you return:
return properties[0];
Or
var data = [
{
"Name": "TEST",
"deviceId": "",
"CartId": "",
"timestamp": 1383197265540,
"FOOD": [],
"City": "LONDON CA"
}
]; // Or whatever the Json is
data = data[0];
Or if you're accessing the json via another object
var data = jsonObj[0];
var tmpStr = '[
{
"Name": "TEST",
"deviceId": "",
"CartId": "",
"timestamp": 1383197265540,
"FOOD": [],
"City": "LONDON CA"
}
]';
var newStr = tmpStr.substring(1, tmpStr.length-1);
See this codepen example