Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send Object as string, not JSON, via Node Express

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.

like image 797
Ivan Avatar asked Mar 03 '23 19:03

Ivan


1 Answers

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 &quot;), 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).

like image 171
Quentin Avatar answered Mar 05 '23 09:03

Quentin