JSON.parse incorrect string format - javascript

i have this string:
"{\\'Ovcount\\':\\'0\\',\\'S1\\':\\'LU\\',\\'S2\\':\\'NewClientOrMove\\',\\'memoToDisplay\\':\\'LU -- New Client or Move\\\"}";
and i want it to become like this:
'{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU -- New Client or Move"}'
I tried with stringify and replace and i ended up with
"{'Ovcount':'0','S1':'LU','S2':'NewClientOrMove','memoToDisplay':'LU -- New Client or Move"}"
And from here i wanted to replace the single quotation marks ' with double quotation marks " but when i did, in beginning and ending of the string appeared an extra "\
"\ "{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU -- New Client or Move\"}\ ""
Any tips on how to get the correct format?

var result = "{\'Ovcount\':\'0\',\'S1\':\'LU\',\'S2\':\'NewClientOrMove\',\'memoToDisplay\':\'LU -- New Client or Move\"}"
.replaceAll("'", '"')
.replaceAll('\\', '');
console.log(result);
this got me what you wanted, it replaces all the single quotes with double quotes, then it removes any back slashes
the result is
'{"Ovcount":"0","S1":"LU","S2":"NewClientOrMove","memoToDisplay":"LU
-- New Client or Move"}'

Related

Parse JSON but preserve \n in strings

I have this JSON string:
{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}
I can parse it when I do this:
pg = JSON.parse(myJSONString.replace(/\\/g, ""));
But when I access pg.text the value is:
Line 1nLine 2.
But I want the value to be exactly:
Line 1\nLine 2
The JSON string is valid in terms of the target program which interprets it as part of a larger command. It's Minecraft actually. Minecraft will render this as you would expect with Line 1 and Line 2 on separate lines.
But I'm making a editor that needs to read the \n back in as is. Which will be displayed in an html input field.
Just as some context here is the full command which contains some JSON code.
/summon zombie ~ ~1 ~ {HandItems:[{id:"minecraft:written_book",Count:1b,tag:{title‌​:"",author:"",pages:‌​["{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}"]}},{}]}
Try adding [1] at /\[1]/g but works for single slash only, but since the type of the quoted json i think is a string when you parse that it slash will automatically be removed so you don't even need to use replace. and \n will remain as.
var myString ='{\"text\":\"Line 1\\nLine 2\",\"color\":\"black\"}';
console.log(JSON.parse(myString.replace(/\\[1]/g, ""))); //adding [1] will remove single slash \\n -> \n
var myString =JSON.parse(myString.replace(/\\[1]/g, ""));
console.log(myString.text);
Your string is not valid JSON, and ideally you should fix the code that generates it, or contact the provider of it.
If the issue is that there is always one backslash too many, then you could do this:
// Need to escape the backslashes in this string literal to get the actual input:
var myJSONString = '{\\"text\\":\\"Line 1\\\\nLine 2\\",\\"color\\":\\"black\\"}';
console.log(myJSONString);
// Only replace backslashes that are not preceded by another:
var fixedJSON = myJSONString.replace(/([^\\])\\/g, "$1");
console.log(fixedJSON);
var pg = JSON.parse(fixedJSON);
console.log(pg);

Replace all \" with \\" in javascript

I want to replace all \" in my string with \\" (\" in <div style=\"font-size:0.9em\">)
var str = '{"CarID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\"font-size:0.9em\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}';
str = str.replace(/\"/g, '\\\\"');
I want the output is (\" in style is replaced by \\"):
{"VehicleID":"Z100","alerts":[{"AlertType":"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>"}],"customizedLocations":[]}
But actually I get is (ALL " is replaced by \\"):
{\\"VehicleID\\":\\"Z100\\",\\"alerts\\":[{\\"AlertType\\":\\"Head <b>southeast</b> on <b>Tân Hải</b> toward <b>Trường Chinh</b><div style=\\"font-size:0.9em\\">Pass by nhan cuoi dep (on the right)</div>\\"}]}
I don't want to use jQuery, can somebody help me!
There is a little problem in your regex. The backslash \ means escape. So when you write \" it finds only one quotation mark, the backslash escapes it as it is a special character.
You have to escape both the backslash and the quotation mark:
str = str.replace(/\\\"/g, '\\\\"');
This will produce the wished result.
Please read the comment from the user zerkms below your question. I don't really understand what this replacing is good for. Maybe you have the so called x-y problem:
https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem
EDIT:
The above posted code line want work, because of the reasons explained in the comment below from the user zerkms. There is a workaround using raw string:
String.raw`\"`.replace(/\"/g, '\\"');
This is tested and should work.
If you are fetching a path from HTML input tag and you need to replace the \ in path with \\ for further processing in code. You can use the following
var myString = $('#myID').val(); // c:\User\path
console.log(myString.split('\\').join('\\\\')); // c:\\User\\path

javascript replace escaped " to work with Json parse

This is the input of javacript function that arise error after Json.parse
I know double escape string is working with JSON.parse, but how to convert current string to that one... I have tried couple of things, but couln't make it work.
pVis = '[{"Name":"Ecz., - \" Europharma\" \" -\"","Id":"402872"}]';
console.log('before replace'+pVis);
pVis = pVis.replace(/\\/g,"\\\\");
//pVis = '[{"Name":"Ecz., - \\" Europharma\\" \\" -\\"","Id":"402872"}]';
console.log('after replace'+pVis);
pVisitedsJson = JSON.parse(pVis);
Since it's interpreting ' character as escaped, it's impossible for me catch and change it on javascript side. So, I changed from the source.

Javascript:Replace single characters after the string

I'm trying to do something which seems fairly basic, but can't seem to get it working.
I'm trying to strip the characters after the last instance of an underscore.
I have this long Query String:
json_data=demo_title=Demo+title&proc1_script=script.sh+parameters&proc1_chk_make=on&outputp2_value=&demo_input_description=hola+mundo&outputp4_visible=on&outputp4_info=&inputdata1_max_pixels=1024000&tag=&outputp1_id=nanana&proc1_src_compresion=zip&proc1_chk_cmake=off&outputp3_description=&outputp3_value=&inputdata1_description=input+data+description&inputp2_description=bien%3F&inputp3_description=funciona&proc1_cmake=-D+CMAKE_BUILD_TYPE%3Astring%3DRelease+&outputp2_visible=on&outputp3_visible=on&outputp1_type=header&inputp1_type=text&demo_params_description=va+bien&outputp1_description=&inputdata1_type=image2d&proc1_chk_script=off&demo_result_description=win%3F&outputp2_id=nanfdsvfa&inputp1_description=funciona&demo_wait_description=boh&outputp4_description=&inputp2_type=integer&inputp2_id=papapa&outputp1_value=&outputp3_id=nananartrtrt&inputp3_id=pepepe&outputp3_type=header&inputp3_visible=+off&outputp1_visible=on&inputdata1_id=id_lsd&outputp4_value=&inputp2_visible=on&proc1_source=lsd-1.5.zip&inputp3_value=si&proc1_make=-j4+-C+&images_config_file=cfgmydemo.cfg&outputp2_type=header&proc1_subdir=xxx-1.5&proc1_url=http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...&inputdata1_image_depth=1x8i&inputp1_id=popopo&inputp1_value=si&inputp2_value=no&demo_data_filename=data_saved.cfg&inputdata1_info=info_lsd&outputp3_info=&inputdata1_image_format=.pgm&outputp1_info=&inputdata1_compress=False&inputp1_visible=on&proc1_id=lsd&outputp4_id=nana&outputp2_description=&outputp4_type=header&outputp2_info=&inputp3_type=float&&tag&inputp4_iddcksmdclk&inputp4_typetext&inputp4_descriptionkldmsclk&inputp4_valueklcdmkl&inputp4_infoclkdmscdl
Now I replace the separator = in separator %24+ and & in +%23+ using fr=fr.replace(/\&/g,"+%23+");
Separator
javascript Mako
= %24+
& +%23+
But the result is:
json_data%24+demo_title%24+Demo+title+%23+proc1_script%24+script.sh+parameters+%23+proc1_chk_make%24+on+%23+outputp2_value%24++%23+demo_input_description%24+hola+mundo+%23+outputp4_visible%24+on+%23+outputp4_info%24++%23+inputdata1_max_pixels%24+1024000+%23+tag%24++%23+outputp1_id%24+nanana+%23+proc1_src_compresion%24+zip+%23+proc1_chk_cmake%24+off+%23+outputp3_description%24++%23+outputp3_value%24++%23+inputdata1_description%24+input+data+description+%23+inputp2_description%24+bien%3F+%23+inputp3_description%24+funciona+%23+proc1_cmake%24+-D+CMAKE_BUILD_TYPE%3Astring%3DRelease++%23+outputp2_visible%24+on+%23+outputp3_visible%24+on+%23+outputp1_type%24+header+%23+inputp1_type%24+text+%23+demo_params_description%24+va+bien+%23+outputp1_description%24++%23+inputdata1_type%24+image2d+%23+proc1_chk_script%24+off+%23+demo_result_description%24+win%3F+%23+outputp2_id%24+nanfdsvfa+%23+inputp1_description%24+funciona+%23+demo_wait_description%24+boh+%23+outputp4_description%24++%23+inputp2_type%24+integer+%23+inputp2_id%24+papapa+%23+outputp1_value%24++%23+outputp3_id%24+nananartrtrt+%23+inputp3_id%24+pepepe+%23+outputp3_type%24+header+%23+inputp3_visible%24++off+%23+outputp1_visible%24+on+%23+inputdata1_id%24+id_lsd+%23+outputp4_value%24++%23+inputp2_visible%24+on+%23+proc1_source%24+lsd-1.5.zip+%23+inputp3_value%24+si+%23+proc1_make%24+-j4+-C++%23+images_config_file%24+cfgmydemo.cfg+%23+outputp2_type%24+header+%23+proc1_subdir%24+xxx-1.5+%23+proc1_url%24+http%3A%2F%2Fwww.ipol.im%2Fpub%2Falgo%2F...+%23+inputdata1_image_depth%24+1x8i+%23+inputp1_id%24+popopo+%23+inputp1_value%24+si+%23+inputp2_value%24+no+%23+demo_data_filename%24+data_saved.cfg+%23+inputdata1_info%24+info_lsd+%23+outputp3_info%24++%23+inputdata1_image_format%24+.pgm+%23+outputp1_info%24++%23+inputdata1_compress%24+False+%23+inputp1_visible%24+on+%23+proc1_id%24+lsd+%23+outputp4_id%24+nana+%23+outputp2_description%24++%23+outputp4_type%24+header+%23+outputp2_info%24++%23+inputp3_type%24+float+%23++%23+tag+%23+inputp4_iddcksmdclk+%23+inputp4_typetext+%23+inputp4_descriptionkldmsclk+%23+inputp4_valueklcdmkl+%23+inputp4_infoclkdmscdl
Now I am interested how to replace this = after the value jsondata.
Explain:
In the Query string there is the string json_data+%23+ and this +%23+ I want replace to =
How?
Strip the characters after the last instance of an underscore:
json_data.substring(0, json_data.lastIndexOf("_"));
Replace +%23+ with =
json_data.replace("+%23+", "=");
However, if you're trying to turn all the %xx into what they're supposed to be, you should url decode the string instead.
Which would probably have to be something like:
decodeURIComponent((json_data).replace('+', '%20'));

How to add single quote in the variable in Javascript?

I have variable var str as following:
var str = <option value="1">tea</option>;
I would like to make it as below
var quote_str = '<option value="1">tea</option>;'
Is there anyone can help me? Thanks in advance!
Edit:
I have tried the following code,however, it's not correct.
var quote_str = 'str';
I think that you want the semicolon outside the string literal:
var quote_str = '<option value="1">tea</option>';
If you mean that you want apostrophe characters inside the string also, you can use \' to put an apostrophe in a string delimited by apostrophes:
var quote_str = '\'<option value="1">tea</option>\'';
You can also use quotation marks to delimit the string. Then you don't have to escape the apostrophes, but you have to escape the quotation marks:
var quote_str = "'<option value=\"1\">tea</option>'";
If you already have a string, and want to add apostrophes around it, you concatenate strings:
var quote_str = "'" + str + "'";
Escape each single quote with a back-slash:
var quote_str = '\'<option value="1">tea</option>;\''
…or wrap the string in quotes of a different kind (i.e. double quotes), but be sure to escape the inner double quotes as to not unintentionally close the string:
var quote_str = "'<option value=\"1\">tea</option>;'"
late update: now we have template literals, so the whole thing becomes a breeze:
var quote_str = `'<option value="1">tea</option>;'`
You can escape characters in Javascript with the \. If that's your issue
We can use the backslash () escape character to prevent JavaScript from interpreting a quote as the end of the string.
The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.
Using this method, we can use apostrophes in strings built with ".
'We\'re safely using an apostrophe in single quotes.' We can also use quotation marks in strings built with ".
"Then he said, \"Hello, World!\"";
In my case, i'm unable to use the notation of ${} in rendered Javascript inside Python Mako Templates as it's already using ${} for rendering variables in Mako:
# mako template somewhere
var quote_str = `'${str}'`;
So i just wrote a small function:
# app.js ( a real Javascript file )
function singlequote(text) {
return `'${text}'`;
}
And then I use:
# mako template somewhere
var quote_str = singlequote(str);
# So i'm able to also use something like:
let btn = '<button type="button" onclick="update(' + singlequote(myid) + "," + singlequote(mystate) + ')"> Update </button>';

Categories

Resources