json.stringify is adding extra backslashes in res.send() - json

My API needs to return the following data in it's response.
{ users: 'All users are as follows: [{id: 1}, {id: 2}]'}
It should be a json object with one of the key values is a json array. However, the json array is turned into a string because it needs to be appended onto another string. My code is like this:
const array = [{id: 1}, {id:2}]
const string = 'All users are as follows: ' + JSON.stringify(array)
res.send({users: string})
I use Express for my API. When I check the response in postman it add many backslashed onto the string. However, when I do console.log({a: string}) locally, I don't see any of those slashes.
this is what I see:
{users: "[{\"id\":1}, {\"id\":2}]"}

{users: "[{\"id\":1}, {\"id\":2}]"}
is the json representation of response , in json string is represented by enclosing it with double quotes (") and so if the string itself contains double quotes then it should be escaped.
{ "user": " "name" " } , is invalid you should use { "user" : "\"name\""}
when you print it in console it prints only the escaped charater thats why you don't see " but ".
learn more about javascript grammer at :
https://www.crockford.com/mckeeman.html
when you use JSON.stringify() it converts it into valid JSON string , you cannot send it without it because it will send it as javascript object and not as valid json. using
res.send ({name:"test"}} will send response as [object][object]
so the only way to get what you want is to send the response as text and not JSON:
const array = [{id: 1}, {id:2}]
const string = 'All users are as follows: ' + JSON.stringify(array)
res.send(`{users: "${string}" }`)
here in res.send isntead of {users:string} , we are using "users:string" .
NOTE: its not valid JSON
Output:

Could you please post your code on returning your response.
Anyways, I do it this way.
let object = {name: "Juan Dela Cruz"}
res.send(object)

Related

Angular 7 HTTP GET send JSON object as a parameter

Im trying to send a json structure to a rest service from angular doing something like this
let test5var = {
"test5var1": {
"test5var2": "0317",
"test5var3": "9556"
},
"test5var4": "123",
"test5var": "0000046"
}
let dataPrincipalBlnc = {"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}};
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let params = new HttpParams().set("requestData", dataPrincipalBlnc.toString()).set("authenticationType", this.authType);
return this.http.get(this.url, {params: params});
The result of the request should look like follows:
https://example.com/test?authenticationType=cookie&requestData=%7B%test%22:%7B%22test1%22:%7B%22test2%22:%220317%22,%22test3%22:%7B%22IDIOMA_ISO%22:%22+en%22,%22DIALECTO_ISO%22:%22US%22%7D,%22channel%22:%22INT%22%7D,%22input%22:%7B%22test5%22:%7B%22test5var1%22:%7B%22test5var2%22:%220317%22,%22test5var3%22:%229556%22%7D,%22test5var4%22:%22123%22,%22test5var5%22:%220000986%22%7D%7D%7D%7D
But it is currently sent as:
https://example.com/test?requestData=%5Bobject%20Object%5D&authenticationType=cookie
Any ideas how can I send the json object to looks as the first request? Do I need to manually convert the json to a valid uri format?
In angularJS is working fine just using the following code:
var data = {
"test1": {
"test2": {
"test3": "0317",
"test4": {
"IDIOMA_ISO": " en",
"DIALECTO_ISO": "US"
},
"channel": "INT"
},
"input": {
"test5": test5var
}
}
};
$http.get(url, {
params: {
authenticationType: authType,
requestData: data
}
}).then(success(deferred), error(deferred));
I have also tried using the following code but the result is adding more characters and the backend is failling because it says the JSON is not in a valid format:
encodeURIComponent(JSON.stringify(dataPrincipalBlnc)
?requestData=%257B%2522test%2522%253A%257B%2522test1%2522%253A%257B%2522test2%2522%253A%25220317%2522%252C%2522test3%2522%253A%257B%2522IDIOMA_ISO%2522%253A%2522%2520en%2522%252C%2522DIALECTO_ISO%2522%253A%2522US%2522%257D%252C%2522channel%2522%253A%2522INT%2522%257D%252C%2522input%2522%253A%257B%2522test5%2522%253A%257B%2522test5var1%2522%253A%257B%2522test5var2%2522%253A%25220317%2522%252C%2522test5var4%2522%253A%25229556%2522%257D%252C%2522test5var4%2522%253A%2522123%2522%252C%2522test5var5%2522%253A%25220003303%2522%257D%257D%257D%257D&authenticationType=cookie
Thanks
Regards
Any JSON object being passed to the service should be sent via response body.
You should add valid string parameters only in the url.
Also there is url size limitation for most browsers, so bigger object may lead you to the long url problem.
You are seeing the requestData=%5Bobject%20Object%5D&authenticationType=cookie because it cannot put a JSON object in url query string.
Some characters cannot be part of a URL (for example, the space) and some other characters have a special meaning in a URL: for example, the character # can be used to further specify a subsection (or fragment) of a document; the character = is used to separate a name from a value. A query string may need to be converted to satisfy these constraints. This can be done using a schema known as URL encoding.
Use JSON.stringify when you have a JavaScript Object and you want to convert it to a string (containing a JSON text). This is called serialization.
Regardless to JSON:
Use encodeURIComponent whenever you want to send "problematic" characters in the URL such as &, % etc. The opposite is decodeURIComponent.
Still i would prefer to send the object in the request body.
So in your case use:
let params = new HttpParams()
.set("requestData", encodeURIComponent(JSON.stringify(dataPrincipalBlnc)))
.set("authenticationType", this.authType);
Adding to #nircraft answer (which is very elaborate and good) this implementation seems to does the trick for you,
let test5var = {
"test5var1": {
"test5var2": "0317",
"test5var3": "9556"
},
"test5var4": "123",
"test5var": "0000046"
}
let dataPrincipalBlnc = '{"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}}';
let headers = new HttpHeaders();
headers.append('Content-Type', 'application/json');
let params = new HttpParams().set("requestData", encodeURIComponent(dataPrincipalBlnc)).set("authenticationType", this.authType);
return this.http.get(this.url, {params: params});
In Javascript you can basically enclose a string in '' or "".
When you don't enclose the string specifically I believe it is enclosed with "", thus making your JSON response in need of escape characters when you use stringify.
Enclosing the string like this will make sure that the double quotes will make sure that it won't need escape characters.
Let me know if you have any questions.
I just fixed the issue by defining the data as an object and using just the JSON.stringify:
let dataPrincipalBlnc: object;
let dataPrincipalBlnc = {"test": {"test1": {"test2": "0317","test3": {"IDIOMA_ISO": " en","DIALECTO_ISO": "US"},"channel": "INT"},"input": {"test5": test5var}}};
let params = new HttpParams().set("requestData", JSON.stringify(dataPrincipalBlnc)).set("authenticationType", this.authType);
Thanks for your help
Regards

Removing leading \s from json response

I have a nodejs app. I am retrieving data from bytea column in postgresql db and returning as part of my service's response. I see the below response. How can I get rid of the \s in the response. When I fetch the same data from jsonb column in postgresql db , I don't the leading \s.
\”products\": [
{
\”productId\”: \”82AA90280202\”,
\”productCode\”: \“BHJKKLL\”,
\”productName\”: “\TEST PROD\“,
\”productQuantity\”: 1,
}
]
Use JSON.parse to decode the string back to an object.
If you have the encoded string as follows:
var s = "\"products\": [{\"productId\": \"82AA90280202\",\"productCode\": \"BHJKKLL\",\"productName\": \"TEST PROD\", \"productQuantity\": 1}]"
Then just do this:
var obj = JSON.parse("{" + s + "}")
obj will then hold the data as an object:
{ products:
[ { productId: '82AA90280202',
productCode: 'BHJKKLL',
productName: 'TEST PROD',
productQuantity: 1 } ] }
I'm assuming when you used the “ or ” quote marks in your example, you really meant the straight-up quote ("). I'm also assuming that you meant that this portion of your example:
"\TEST PROD\",
Is a typo and should have been this:
\"TEST PROD\",

Create JSON from a String

I am trying to create a json from this String
var json = { data: [v1,v2], con: [begin: "test1", end: "test2"] };
What is wrong with the String? I get an error SyntaxError: Unexpected token :It is not possible to set a key for the value test1 and test2?
In JavaScript:
An object literal, which uses the {} syntax, consists of a collection of property: value pairs.
An array literal, which uses the [] syntax, consists of a collection of values.
[begin: "test1", end: "test2"]
You have used the array syntax here, but have tried to put property: value pairs inside it.
This causes your error, the : isn't expected.
You probably want to use the {} there. Alternatively, you want to remove begin: and end:.
This has nothing to do with JSON or strings. It is simply JavaScript.
You are instantiating a javascript Object.
const toto = {};
is the same as
const toto = new Object();
This is a String javascript object, which hold a string representation of a json.
const toto = "{ \"key\": \"value\" }";
Try
var json = { data: ["v1","v2"], con: [{begin: "test1"}, {end: "test2"}] };
It looks like you might have a blocking error.

Using JPATH, how do I select a JSON value inside another JSON string?

I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:
{
"results": [{
"paramName": "OutputPolyline",
"dataType": "String",
"value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
}],
"messages": []
}
I use the following code to parse the JSON and grab the value of the "value" key:
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
Console.WriteLine(token.Path + " -> " + token);
The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]
You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.
Thus you need to do something like:
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");
Sample fiddle.

JSON.parse: expected property name or '}'

Data contains (/"/):
{"test":"101","mr":"103","bishop":"102"}
script:
console.log($.parseJSON(result));
I'm getting error,
JSON.parse: expected property name or '}'.
Had same issue when used single quotes in JSON file, changed to double quotes for all string properties/values and it's working OK now.
Change:
JSON.parse("{'wrongQuotes': 5}")
To:
JSON.parse('{"rightQuotes": 5}')
If you're receiving the JSON with the encoded ", you'll have to replace each instance of " with a true " before doing JSON.parse. Something like:
myJSONstring.replace(/"/ig,'"');
My case was even simpler.
Having confused JSON with plain JS, I didn't put the object keys in double quotes.
❌:
{
title: "Hello World!"
}
✅:
{
"title": "Hello World!"
}
The irony is, Postman even highlighted this to me, but I ignored. Sleep is the answer.
For anyone who is using laravel blade and declaring a JS variable in a view.
You need to use:
var json = JSON.parse('{!! $json !!}');
Otherwise you will get this error due to the quotes being parsed as "
Change
{"test":"101","mr":"103","bishop":"102"}
To
'{"test":"101","mr":"103","bishop":"102"}'
if this is coming from the server (PHP)
i.e <?php $php_var = ["test" => "101", "mr" => "103", "bishop" => "102"]?>
then on Javascript end
var javascript_var = $.parseJSON('<?= json_encode($php_var) ?>');
/* suppose your json are single quote, it's necessary replace it single quote before, a simple example*/
let ojson = "{'name':'peterson'}";
ojson = ojson.replace(/'/g, '"');
ojson = JSON.parse(ojson);
console.log(ojson['name'])
for example, if u get something like this
{ "location": "{'lat': 4.6351144, 'lng': -74.12011199999999}" }
from your server, or recently get a bad converted format.
first,get your string
myItemString = "{'lat': 4.6351144, 'lng': -74.12011199999999}"
and change the keys using replace, and later json.parse,
'key' to ---> "key"
const key1 = myItemString.replace("'lat'",'"lat"')
const key12 = key1.replace("'lng'", '"lng"');
const obj = JSON.parse(key12)
console.log(obj)
You can try using stringifying before parsing:
JSON.parse(JSON.stringify(result))