EN
JavaScript - convert json text to string variable
2 points
In this article, we would like to show you how to convert JSON text to string variables in JavaScript.
xxxxxxxxxx
1
function parseString(json) {
2
var text = JSON.parse(json);
3
4
if(typeof(text) == 'string') {
5
return text;
6
}
7
8
throw new Error('Incorrect type!');
9
}
10
11
// Example:
12
13
var json = '"This is example text..."';
14
var text = parseString(json);
15
16
console.log(text);
xxxxxxxxxx
1
var JsonUtils = new function() {
2
var expression = /(\\*)"/g;
3
4
function getContent(json) {
5
if (json) {
6
var limit = json.length - 1;
7
8
if (json[0] == '"' && json[limit] == '"') {
9
return json.substring(1, limit);
10
}
11
}
12
13
return null;
14
}
15
16
this.parseString = function(json) {
17
var content = getContent(json);
18
19
if (content) {
20
var result = content.replace(expression, function(value, escape) {
21
if(escape.length % 2) {
22
var result = '';
23
24
for(var i = 1; i < escape.length; i += 2) {
25
result += '\\';
26
}
27
28
return result + '"';
29
}
30
31
throw new Error('Incorrect json format!');
32
});
33
34
return result;
35
}
36
37
throw new Error('Incorrect json format!');
38
}
39
};
40
41
// Example:
42
43
var json = '"Example SQL query: \\"SELECT * FROM `users`;\\""';
44
var text = JsonUtils.parseString(json);
45
46
console.log(text);