Ok, I want the response to be a plain string, not JSON.
Ex. this object
let obj = {
foo: 'bar',
baz: 1
}
Should be returned as
"{foo: 'bar', baz: 1}"
Instead of
{"foo": "bar", "baz": 1}
Why? I need to use the string as a link in quickchart
<img src="https://quickchart.io/chart?c={type:'line',data:{labels:['January','February', 'March','April', 'May'], datasets:[{label:'Dogs', data: [50,60,70,180,190], fill:false,borderColor:'blue'},{label:'Cats', data:[100,200,300,400,500], fill:false,borderColor:'green'}]}}">
The double quotes in JSON break the image link.
Or, maybe suggest a better way.
The double quotes in JSON break the image link.
You have an XY problem .
The problem is that using "
characters in an attribute value delimited by "
characters will break the attribute value.
While avoiding using "
characters in the data is a solution, it isn't a good one (largely because avoiding them without breaking other stuff is hard). A better solution is to correctly escape them.
const json = JSON.stringify(obj);
const url_escaped_json = encodeURIComponent(json);
const img = `<img src="https://quickchart.io/chart?c=${url_escaped_json}" alt="...">`;
Note that this doesn't use HTML escaping (which would replace "
with "
), because you are putting the data into a URL so it needs URL escaping first (and that will replace "
with %20
rendering the HTML escaping unneeded).
You might leverage a dedicated API for that like Image-Charts that handles such encoding issue nicely:
https://image-charts.com/chart?cht=lc
&chd=a:50,60,70,180,190|100,200,300,400,500
&chs=900x400
&chdl=Dogs|Cats&chdlp=t&chdls=444444,15
&chxt=x,y
&chxl=0:|January|February|March|April|May
&chg=1,1
&chco=0018F5,377E22
Disclaimer: I'm Image-Charts founder.
You can use JSON.stringify
for this.
let obj = {
foo: 'bar',
baz: 1
}
console.log(JSON.stringify(obj));
This will convert the object into string.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.