Adding quotation makes to JSON String which contains some XML values - javascript

I'm trying to format a JSON input string in Javascript so that I can use it as a map.
{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}
To do this I need to put quotation marks around each key and value. Like here:
{
"accountNumber": "12345",
"paymentMethodObject": "<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>",
"preview": "true"
}
The problem is when I try to do it, quotes get added to the XML values also because they also contain a colon.

Maybe you need to use method replace with pattern Regex that match key:value replace it with surrounded by quotes pair!
let strJSON = '{accountNumber:E22E6178D16777E1E053020011AC64B0,paymentMethodObject:<ns2:Token>123</ns2:Token><ns2:Type>CreditCard</ns2:Type>,preview:true}';
let objJSON = strJSON.replace(/(\w+):([\/<>:\w+]+)/g,'"$1":"$2"');
console.log(objJSON)

Related

String replace with with unescaped curly brace in JSON

I'm trying to replace a value in a string with a double curly (used by postman for variable substitution), but every time I try to quote or escape the braces, I always get additional escaped quotes or double escaped braces, all of which break the substitution:
Original String:
"header": [{"key": "x-device-auth","value": "\"token\""}]
OriginalString.replace('token','{{token}}')
Result:
"header":[{"key":"x-device-auth","value":"\"{{token}}\""}]
If I search for .replace('\"token\"','{{token}}'), I don't get a match. The final string needs to be:
"header": [{"key": "x-device-auth","value": "{{token}}"}]
You should be looking for token with the escaped wrapping double quotes, since you also want to replace those.
var originalString = '"header": [{"key": "x-device-auth","value": "\\"token\\""}]';
console.log(originalString);
console.log(originalString.replace('\\"token\\"','{{token}}'));
originalString = '"header": [{"key": "x-device-auth","value": "\"token\""}]';
console.log(originalString);
console.log(originalString.replace('"token"','{{token}}'));
I have added two cases, one with the original string actually containing backslashes (first originalstring definition). The second without. Choose the one, that best matches your actual input :-)
I dont see the input string is having proper escape characters applied. As you posted question in javascript tag, I tried below with javascript and its giving required results.
var str = "\"header\": [[{\"key\": \"x-device-auth\",\"value\": \"token\"}]";
var res = str.replace('token','{{token}}');

Parse the json string without quotes into json

Following json string is not converting into json as key is not inside quote.
{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}
I have tried:
JSON.parse -- it does not work as keys are not inside quotes.
eval('('+str+')') -- not converting for some reason, also little reluctant for this solution due to security.
Manually insert double quotes delimiting colon (:) but one of my
value, which is a url, too has a colon, as given in the solution:
regular expression add double quotes around values and keys in javascript
Why is it difficult to convert this string into json and how to convert it?
var s = '{file:"http://video.test.com/media/myvideo.mp4", image:"/category/dt/filename.png", width:"100%", height:"100%", stretching:"uniform", autostart:true, modes:[{type:"flash", src:"/swf/external/player.swf"}, {type:"html5"}]}';
console.log(eval('(' + s + ')'));
The main question is really where did you get the string from, but anyways, here is a solution.
var obj = eval('(' + str + ')');
var json = JSON.stringify(obj);

JS - parsing data with random single quotes

How do I parse an array of objects if it contains single quote characters?
For example, I have:
$example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
The single quotes seem to break up the array, making parsing impossible.
You can use backticks (``). It will generate the string as it was written, with double "" and single ' quotes.
var str = `{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}`;
console.log(str);
var obj = JSON.parse(str);
console.log(obj.response[0].uid);
It's a json string not an object.
Use JSON.parse(myJsonSting) and you will get objects with the ' taken care of.
Javascript is supposed to ignore single quotes if it is inside double quotes, in your case try adding backslash before the single quote.
To parse at json string to object
var example = '{"response":[{"uid":3202935,"first_name":"Martha","last_name":"O'Nill","user_id":3202935},{"uid":4070530,"first_name":"Alex","last_name":"White","user_id":4070530}]}';
var objExample = JSON.parse(example);
To convert json object to json string
var StrExample = JSON.stringify(objExample);

How to extract expected value from string, html input submission

Is there a way to extract an expected value from a string within an html input submission?
If the following is a single submission, and its parts delimited by double quotes here only for clarity, is there a way to set the expected value, as well as the trailing string, to variables?:
"expected-value" "second part of same input string, the quotes arent real"
ex.
var exp = "expected-value";
var trail = "second part of same input string, the quotes arent real";
Upon input submission how to parse string and extract each and to their variables?
Use Javascripts split method and a proper delimiter and you can 'split' the string into an array, and then access the different parts of the array.
I would avoid the double quotes. You'll have to figure out how and where your delimiter is, but split is pretty flexible in those regards.
$text = "expected-value|second part of same input string, the quotes arent real";
result = $text.split('|');
var exp = result[0];
var trail = result[1];
console.log(exp);
console.log(trail);
// output:
// expected-value
// second part of same input string, the quotes arent real
To get the value from a text input you would use something like:
document.getElementById('textbox_id').value
Split method documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

javascript parse string as object or JSON

I want to be able to define a hash pair inside an html element as an attribute and then parse it into an object to be processed by javascript.
example:
<div id="test" mydata="{'xkey':'xval','ykey':'yval'}">
<script>
var mydata = JSON.parse($('#test').attr('mydata'));
console.log(mydata.xkey);
</script>
But the problem is it is not being converted into an object and the output is undefined.
How can I achieve this ??
Use double quotes instead, to surround keys and string values:
mydata='{"xkey":"xval","ykey":"yval"}'
DEMO: http://jsfiddle.net/reAtQ/
If you must keep the surround double quotes, you can encode the inner ones:
mydata="{"xkey":"xval","ykey":"yval"}"
DEMO: http://jsfiddle.net/reAtQ/1/
Or, you could replace all single quotes with double quotes before parsing:
var mydata = JSON.parse($('#test').attr('mydata').replace(/'/g, '"'));
DEMO: http://jsfiddle.net/reAtQ/2/
Although note that if any of the keys/values contain a single quotes, they will be inadvertently replaced.
Reference:
in JSON, Why is each name quoted?

Categories