According to this question ( link ) I have a JSON with values that I extract from HTML elements with the difference of using <textarea>
instead of <select>
and whose values are obtained from texts of MS Word files. I build my JSON as follows:
var trads = $("select[name='personal[]']").map(function(){return $(this).val();}).get();
var num_trad = trads.length;
var text = new Array();
var values = new Array();
var approved = new Array();
for (var i=1; i<=num_trad; i++){
text.push($("textarea[name='lang_"+i+"[]']").map(function(){return $(this).val();}).get());
values.push($("input[name='words_"+i+"[]'").map(function(){return $(this).val();}).get());
approved.push($("input[name='approved_"+i+"[]'").map(function(){return $(this).val();}).get());
}
var lenguajes=10;
var sjson=`[`;
for (var i=0; i<num_trad; i++){
sjson+=`{"personal": "${trads[i]}","content": [`;
for(var h=0; h<lenguajes&&langs[i][h]!=undefined; h++){
sjson+=`{"text":"${langs[i][h]}",`;
sjson+=`"words":"${values[i][h]}",`;
sjson+=`"approved":"${approved[i][h]}"}`;
if(langs[i][h+1]!=undefined)
sjson+=',';
}
sjson+=']}';
if(i+1<num_trad)
sjson+=',';
}
sjson+=']';
console.log(sjson);
However, some Word documents contain quoted text and embedding it in the JSON gives me an error, for example:
[{
"personal": "1001",
"content": [{
"text": "Los lenguajes que mencionó son: "Español e Inglés"",
"words": "302",
"approved": "yes"
}, {
"text": "Ella dijo: "Me gustan los helados"",
"words": "180",
"approved": "no"
}]
}]
Which is an invalid JSON.
How can I solve that?
I will appreciate your help.
There are 2 options:
1. Replace double quotes with single quotes:
For this you can use
split()
andjoin()
in the following way:result:
You can see how it works in the following code:
2. Replace the double quotes and add a backslash:
For this you can also use
split()
andjoin()
in the following way:result:
The advantage of this method is that the double quotes will be preserved when displaying the text.
You can see how it works in the following code:
You can check (with https://jsonlint.com/ for example) that in both cases the json are valid.
I hope it helps you, greetings.