I want to remove some special character from json without parsing
the json into object.
Parsing would result into error that is why i wanted to do without json.parse().
below is my json:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
desired output:
{
"id":324,
"name":"first",
"body":{
"sbody": "<p> The New Stroy </p>"
}
}
Looks like your input is a string and the error you are getting is when using JSON.parse.
Try this
var response = '{"sbody": "<p>\\\The New Stroy\\\</p>"}';
response = response.replace(/\\/g, "");
var obj = JSON.parse(response);
console.log(obj);
You need to run .replace on your string:
var string = '{"id":324,"name":"first","body":{"sbody":"<p>\\\The New Stroy\\\</p>"}}';
string = string.replace(/\\/g,'');
console.log(string);
//{"id":324,"name":"first","body":{"sbody":"<p>The New Stroy</p>"}}
The reason the pattern is /\\/ is because \ is used to escape characters. With a single \ we end up escaping the /. What we need to do here is escape the escape character to turn it into a literal string character: \\.
The g after the pattern means to search for the pattern "globally" in the string, so we replace all instances of it.
var obj = {
"id":324,
"name":"first",
"body":{
"sbody": "<p>\\\The New Stroy\\\</p>"
}
}
// Convert object to string
var str = JSON.stringify(obj);
// Remove \ from the string
var convertedStr= str.replace(/\\/g,'');
// Convert updated string back to object
var newObj = JSON.parse(convertedStr);
Related
I have a huge JSON stringified into a string like this one:
"\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}"
I need to JSON.parse it to use as an object. Do you know any way to decode it?
I tried decodeURIComponent(), unescape(), different variants of .replace( /\\u/g, "\u" ) and I can not get it into the needed form.
You can convert UTF-16 to text using the following function:
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
Demo:
const r = utf16ToText("\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d");
console.log("As text: ", r);
const j = JSON.parse(r);
console.log("As JSON: ", j);
console.log("JSON Prop: ", j.name);
function utf16ToText(s) {
return s.replace(/\\u[0-9a-fA-F]{4}/gi, match => {
return String.fromCharCode(parseInt(match.replace(/\\u/g, ""), 16));
});
}
If your string is valid JSON, then you can use JSON.parse() to process the UTF16 for you. To make what you have valid JSON, you have to add double quotes to each end (inside the actual string) as all strings must be enclosed in double quotes in the JSON format. Here's an example:
let data = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d";
// to make this legal JSON so we can let the JSON parser parse it for us and
// handle the UTF16 for us, we need to put double quotes in the actual string at each end
// Then, it's legal JSON and we can parse it
let str = JSON.parse('"' + data + '"');
console.log(str);
console.log("type is", typeof str);
This gives you a result in string form:
{"name":"Test"}
This result is now legal JSON on its own. If you then wanted to parse that as JSON, could just call JSON.parse() on it again to turn it into an actual Javascript object:
let data = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022\\u007d";
let str = JSON.parse('"' + data + '"'); // decoded string here
// now take the string and actually parse it into a Javascript object
let obj = JSON.parse(str);
console.log(obj); // Javascript object here
console.log("type is", typeof obj);
This gives you a resulting live Javascript object:
{name:"Test"}
The first call to JSON.parse() just takes your JSON string and decodes it into a Javascript string. Since that Javascript string is now also legal JSON for an object definition, you can call JSON.parse() on it again to turn it into a Javascript object.
Thank you for your input. Because of that, I got the solution:
let a = "\\u007B\\u0022name\\u0022\\u003A\\u0022T\\u0065st\\u0022}" original string
let b = '"' + a + '"' adding " in order to make a valid stringified JSON
let c = JSON.parse(b) that will produce a partially decoded string (partially because some of the \uXXXX characters can stay in the string)
let solution = JSON.parse(c) that will create an object with all the characters decoded
Big thanks to #jfriend00
I have a string variable with array data .
var str = "[\r\n 10,\r\n 20\r\n]" ;
I want to convert above string to array like using javascript .
Output :-
var arr = [10,20];
You can simply use JSON.parse - it will ignore the newlines and convert the string representation of an array to a JavaScript array:
var str = "[\r\n 10,\r\n 20\r\n]" ;
var arr = JSON.parse(str);
console.log(Array.isArray(arr))
console.log(arr)
You need only to parse that string as a JSON, because it is clearly an array.
So this is the procedure:
var str = "[\r\n 10,\r\n 20\r\n]";
const myArray = JSON.parse(str);
console.log(myArray);
UPDATE:
If you are wondering why those special chars (\r\n) are going away:
// a string
const str = "[\r\n 10,\r\n 20\r\n]";
// if I print out this, Javascript, will automatically replace those special
// chars with what they means (new line)
console.log(str);
console.log(typeof(str));
// so if we are going to parse our string to the JSON parser
// it will automatically transform the special chars to new lines
// and then convert the result string "[10,20]" to an array.
const myArray = JSON.parse(str);
console.log(myArray);
console.log(typeof(myArray));
So I have a RegExp regex = /asd/
I am storing it as a as a key in my key-val store system.
So I say str = String(regex) which returns "/asd/".
Now I need to convert that string back to a RegExp.
So I try: RegExp(str) and I see /\/asd\//
this is not what I want. It is not the same as /asd/
Should I just remove the first and last characters from the string before converting it to regex? That would get me the desired result in this situation, but wouldn't necessarily work if the RegExp had modifiers like /i or /g
Is there a better way to do this?
If you don't need to store the modifiers, you can use Regexp#source to get the string value, and then convert back using the RegExp constructor.
var regex = /abc/g;
var str = regex.source; // "abc"
var restoreRegex = new RegExp(str, "g");
If you do need to store the modifiers, use a regex to parse the regex:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var parts = /\/(.*)\/(.*)/.exec(str);
var restoredRegex = new RegExp(parts[1], parts[2]);
This will work even if the pattern has a / in it, because .* is greedy, and will advance to the last / in the string.
If performance is a concern, use normal string manipulation using String#lastIndexOf:
var regex = /abc/g;
var str = regex.toString(); // "/abc/g"
var lastSlash = str.lastIndexOf("/");
var restoredRegex = new RegExp(str.slice(1, lastSlash), str.slice(lastSlash + 1));
const regex = /asd/gi;
converting RegExp to String
const obj = {flags: regex.flags, source: regex.source};
const string = JSON.stringify(obj);
then back to RegExp
const obj2 = JSON.parse(string);
const regex2 = new RegExp(obj2.source, obj2.flags);
Requires ES6+.
You can use the following before storage of your regex literal:
(new RegExp(regex)).source
See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp/source
Example:
regex = /asd/
string = (new RegExp(regex)).source
// string is now "asd"
regex = RegExp(string)
// regex has the original value /asd/
let rx = RegExp.apply(RegExp, str.match(/\/(.*)\/(.*)/).slice(1));
A modified version of #PegasusEpsilon answer
StackOverflow saves the day again, thanks #4castle! I wanted to store some regex rules in a JS file, and some in a DB, combine them into an array of objects like so:
module.exports = {
[SETTINGS.PRODUCTION_ENV]: [
{
"key": /<meta name="generator"[\s\S]*?>/gmi,
"value": "",
"regex": true
},
...
]
}
Then, loop through each environment's objects and apply it to a string of text. This is for a node/lambda project, so I wanted to use ES6. I used #4castle's code, with some destructuring, and I ended up with this:
let content = body;
const regexString = replacement.key.toString();
const regexParts = /\/(.*)\/(.*)/.exec(regexString);
const {1: source, 2: flags} = regexParts;
const regex = new RegExp(source, flags);
content = content.replace(regex, replacement.value);
return content;
Works a treat!
How can I transform the string "Test(5)" into "Test\(5\)" dynamically? (JQuery or Javascript)
I have tried this but with no success
var string = "Test(5)";
string = string.replace("(","\(");
string = string.replace(")","\)");
console.log(string);
http://jsfiddle.net/mvehkkfe/
I assume you meant
replace the string "Test(5)" into "Test\(5\)"
In which case:
var string = "Test(5)";
string = string.replace("(","\\(");
string = string.replace(")","\\)");
console.log(string);
Escape the backslash
If you want to replace the string "Test(5)" into "Test\(5\)", you can use below code
var string = "Test(5)";
string = string.replace("(","\\(");
string = string.replace(")","\\)");
console.log(string);
Suppose I have this simple JSON:
{"test":"test"}
Now I want to convert it into the following format:
{\"test\":\"test\"}
I have found some of the solutions of replacing double quotes with backslash and double quotes but all those works on text format.
I need to pass this kind of format to AWS SNS as message parameter.
As I suggested in comment
You can go from a Javascript object to an escaped JSON using JSON.stringify twice
var myObject = {"test":"test"};
var myJson = JSON.stringify(myObject); // {"test":"test"}
var myEscapedJson = JSON.stringify(myJson); // "{\"test\":\"test\"}"
You may convert the JSON object to a string format first by using JSON.stringify()
var temp = {"test":"test"};
var tempStr = JSON.stringify(temp);
console.log(tempStr); //> {"test":"test"}
var modifiedStr = tempStr.replace(/"/g, '\\"');
console.log(modifiedStr); //> {\"test\":\"test\"}
If your want to just encode only the open and close double quote, you may try this
var temp = {"test":'te"st'};
var tempObj = JSON.parse(JSON.stringify(temp));
for(var k in tempObj){
tempObj[k]=tempObj[k].replace(/"/g, "<DOUBLE_QUOTES_4594>");
}
var tempStr = JSON.stringify(tempObj);
console.log(tempStr); //> {"test":"te<DOUBLE_QUOTES_4594>st"}
var modifiedStr = tempStr.replace(/"|"/g, '\\"').replace(/<DOUBLE_QUOTES_4594>/g, '"');
console.log(modifiedStr); //> {\"test\":\"te"st\"}