how to remove backslash added json.stringify - json

i'am currently working on a object to string conversion and upon reading i need to use json.stringify. I have successfully converted it, however when i try to input a backslash on my javascript object the conversion adds another backslash.
Scenario:
on my object variable i used "\r\n" after using the json.stringify the result was "\r\n" which should be only "\n" as i used the .replace function
var str = JSON.stringify(item.NotesContent);
var exp1 = str.replace(/\r\n/g, "\\\\n");
console.log("your new string is : " + exp1);
Result
any inputs for this?

Related

NodeJS create JSON array for Slack incoming webhook

I am currently working on getting my incoming Webhook application written in Node.JS to get work with this API: https://api.slack.com/incoming-webhooks.
My problem is that the JSON string for Slack has to configured with " these quotation marks and if I create a simple JSON string in Node.JS, Slack says that the string isn't valid.
var text = "New Commit";
var form = '{"text": "' + text + '" }';
The above code works, but looks pretty ugly and when I add a \n' to indicate a new line, the \n is directly converted into a new line and not sent within the string, so Slack says again the JSON string isnt valid.
As mentioned by tandrewnichols I need to use JSON.stringify and create an object.

cordova readAsText returns json string that can't be parsed to JSON object

I read my json file using http and cordova file readAsText functions.
http request returns an object which is ok.
cordova file readAsText function return 'string' which contain extra "r\n\" symbols. This make it impossible to use JSON.parse(evt.target.result)
function readJson(absPath, success, failed){
window.resolveLocalFileSystemURL(absPath, function (entry) {
entry.file(function (file) {
var reader = new FileReader();
reader.onloadend = function (evt) {
success(evt.target.result);
};
reader.readAsText(file);
}, failed);
}, failed);
}
readJson(cordova.file.dataDirectory + 'my.json', function(res){
console.log(JSON.parse(res)); //here I've got an parsing error due to presence of r\n\ symbols
}, failed );
How to read JSON files using cordova?
UPDATE:
funny thing that the following works:
a = '{\r\n"a":"1",\r\n"b":"2"\r\n}';
b = JSON.parse(a);
so the problem not only with \r\n... there is something else that is added by cordova readAsText
UPDATE2
as a workaround I use now var object = eval("(" + res + ")")
Still search for a common way to load json objects...
No one has answered this and I just had to solve it for my project, so I will post my solution.
The readAsText method outputs a string, so you CAN actually run a replace on it, but what you need to do is use a RegExp to find the newline character. here's my solution:
var sanitizerRegex = new RegExp(String.fromCharCode(10), 'g');
var sanitizedData = JSON.parse(result.replace(sanitizerRegex, ''));
I've used the String method fromCharCode to get the specific newline character and the "g" flag to match all instances in the entire string. The problem with your string solution is that you can't do a string replace using the characters for backslash and "n" because the issue is the actual new line character, which is merely represented as "\n".
I do not know the reason JSON.parse can't handle the newline character, or why the file plugin introduces this problem, but this solution seems to work for me.
Also, NEVER use eval like this if you can avoid it, especially on input from a source like a JSON file. Even in a cordova app, using eval is potentially very unsafe.
I found out the solution after debug deeply. readAsText function returned text has one more letter at the first position of text.
Example:
{"name":"John"} => ?{"name":"John"} (?: API didn't return ?, just one string)
I confirmed this with length of result, so we need to use substr(1) before parse JSON.
fileContent = fileContent.substr(1);
var jData = jQuery.parseJSON(fileContent);

Cannot Parse Json when escaping double quotes

I've created an application that's reading data from http response. The data comes back as JSON and the JSON string contains backslashes where the double quotes are escaped.
I've tried the example demonstrated here, Android: Parsing JSON string inside of double quotes.
Here's my example:
var data="\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\""
var escapeSlashes = data.replace("\\\"/g", "\"");
It returns like this:
[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]
The code breaks when trying to parse.
var obj = $.parseJSON(escapeSlashes);
Is there another way of handling this other than doing a replace?
Alright, so.. it's really just JSON, escaped several times. Super silly thing to do, but how to solve this?
Let's unescape it several times!
Here we go:
var moo = "\"[{\\\"FirstName\\\":\\\"John\\\",\\\"LastName\\\":\\\"Doe\\\"}]\"";
// Don't let the backslashes confuse you
// What the string really contains is here:
console.log(moo);
// "[{\"FirstName\":\"John\",\"LastName\":\"Doe\"}]"
// That's a JSON string, see the quotes at the ends?
// Let's parse!
var moo2 = JSON.parse(moo);
console.log(moo2);
// [{"FirstName":"John","LastName":"Doe"}]
// Alright, looks like a regular JSON array with one object in it.
// Crack it open!
var moo3 = JSON.parse(moo2);
console.log(moo3);
// Hole cow, we got a JS Object!
// [Object { FirstName="John", LastName="Doe"}]
// Do whatever you want with it now...
Try it out: http://jsfiddle.net/YC6Hx/

How to escape "\" from JSON string in Titanium?

I have written a native android module where i am returning Json string to JavaScript layer. But in javascript layer , i am getting this json string added with "\" for all "". How to escape this "\" from json string.
Seems that your json is not a "real JSON object" but just a String. This explain why " symbol are escaped. Try to use JSON.parse() in your javascript.
var my_json_string = "{\"my_key\": \"the_value\"}";
var my_json_object = JSON.parse(my_json_string);
// should render something like
// Object {my_key: "the_value"}

Remove empty {} in JSON

I have JSON which is something like this
Var myObj = {{},{'test': '1'}}
I would like to remove the {} so end up like
{'test':'1'}.
How can do this?
This is totally not valid JSON. You'll get an error if you actually try to assign that not-JSON to a variable ("Var" should be lowercase by the way).
You'll need to convert it to a string (actually presumably it is a string already because it's invalid as an object), use a regex to replace the offending invalid JSON, and then convert back to JSON.
var myObjStr = "{{},{'test': '1'}}";
var validMyObjStr = myObjStr.replace(appropriateRegEx, '');
var myObj = eval('(' + validMyObjStr + ')');
If you need it, I can build an appropriate RegEx for you. Just drop a comment. But really, you should probably fix whatever's giving you the invalid JSON in the first place.