EN
JavaScript - convert string variable to json text
7 points
In this article, we would like to show you how to convert string variables to JSON text in JavaScript.
xxxxxxxxxx
1
var text = 'This is example text...';
2
var json = JSON.stringify(text);
3
4
console.log(json);
xxxxxxxxxx
1
var expressions = [
2
// operations order is important
3
{ rule: /\\/g, result: '\\\\' },
4
{ rule: /"/g, result: '\\"' }
5
];
6
7
function serializeString(text) {
8
if(text) {
9
for(var i = 0; i < expressions.length; ++i) {
10
var expression = expressions[i];
11
12
text = text.replace(expression.rule, expression.result);
13
}
14
15
return '"' + text + '"';
16
}
17
18
return null;
19
}
20
21
// Example:
22
23
var text = 'Example SQL query: \"SELECT * FROM `users`;"';
24
var json = serializeString(text);
25
26
console.log(json);