Removing leading \s from json response - json

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\",

Related

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

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)

Flutter: Convert string to Map

I am using SQFlite to store data locally, I have a table in which I have a field called 'json', this field is of type TEXT and stores a json converted to String, such as: '{name: Eduardo, Age: 23, Sex: male}'.
Up to this point, everything works fine.
But then I need to consult this information from the database and how it is stored in a text type format flutter recognizes it as a string. I don't know how to convert it back to an object.
I know that I can build a function to solve this, in the case that the information stored in the json always complies with the same structure. But in my case, the information contained by the json will be variable.
Is there a way to solve this problem?
you can Simply use json.decode function from the dart:convert package.
example:
import 'dart:convert';
main() {
final jsonString = '{"key1": 1, "key2": "hello"}';
final decodedMap = json.decode(jsonString);
// we can now use the decodedMap as a normal map
print(decodedMap['key1']);
}
check those links for more details
https://api.dart.dev/stable/2.10.3/dart-convert/json-constant.html
https://api.dart.dev/stable/2.4.0/dart-convert/dart-convert-library.html
if you have issue that your json keys doesn't have quotes then try this code it transform the unquoted String to a quoted String and then decode it , it's 100% working
final string1 = '{name : "Eduardo", numbers : [12, 23], country: us }';
// remove all quotes from the string values
final string2=string1.replaceAll("\"", "");
// now we add quotes to both keys and Strings values
final quotedString = string2.replaceAllMapped(RegExp(r'\b\w+\b'), (match) {
return '"${match.group(0)}"';
});
// decoding it as a normal json
final decoded = json.decode(quotedString);
print(decoded);
#EduardoColon If the keys are not quoted, then it's not JSON, it's your own custom key-value format. JSON keys have to be quoted. See https://json.org for the "official" JSON syntax.

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

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.

Escaping JSON Payload with back slash

I have an external service that returns a JSON Payload as below
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
How could I escape the back slash? I need to use a json path and currently I cant do it. Is there a better way than String Replace? Thanks.
Regards,
Hari
Just simply parse your JSON string. like that.
var response = {
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
};
var result = $.parseJSON(response.GetIPAResult);
Now you can get your data (in result variable) without back slash.
hari .. at a moment your json structure are as follows
{"key": "value"}
where value is a stringify of {"Data" : JSONARRAY}
here 2 case arise..
case 1:
try to change the structure of return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
case 2:
try to convert return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
by replace "{ with { , \" with " and }" with }
hence the result of
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
to
{
"GetIPAResult": {"Data":[{"Name":"Pan1","Email":"abc#example.com"},{"Name":"Pan2","Email":"xyz#example.com"}]}
}