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))
Related
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)
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
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.
I am using asp.net webapi and returning json response. One of the property in the json response has got a path field. When i check in Console.WriteLine i get the values without additional double slashes. But the json response in postman contains extra double slashes.
Expected:
\\test.com\cax\mef\160704\160704Z003.abc
But in the json response the output i am getting is:
"path": "\\\\test.com\\cax\\mef\\160704\\160704Z004.abc"
And my json settings in webapi.config:
var formatters = GlobalConfiguration.Configuration.Formatters;
var jsonFormatter = formatters.JsonFormatter;
var settings = jsonFormatter.SerializerSettings;
settings.Formatting = Formatting.Indented;
settings.ContractResolver = new CamelCasePropertyNamesContractResolver();
Can anyone help me what is the problem and how to solve this?
Why i am getting extra double slashes?
Thanks
The added slashes are their as Escape characters.
This Could be caused when you asign the URL to the Variable before you return the response via the Webapi. Eg:
xObj.path = urlPath;
----------------
xObj.path = urlPath.ToString();
It All Depends on where and how you Assigned them.. If they are coming for a Database they could have also Been Stored Like that.
it could also just be the IDE showing it to you Like that. This Often Just Adds the Escape characters to the interpretation of the value.. but when the value is used they are no longer present.
this is how you parse the JSON
var jsonResponse = '{ "firstName":"John" , "lastName":"Doe", "path" : "/test/test/adasdasd.com" }';
var obj = JSON.parse(jsonResponse);
console.log(obj);
You Will note that my Example doesn't have the double slashes. That is because if you use the response directly it wont have any either.
This seems like a solved problem but I am unable to find a solution for it.
Basically, I read a JSON file, change a key, and write back the new JSON to the same file. All works, but I loose the JSON formatting.So, instead of:
{
name:'test',
version:'1.0'
}
I get
{name:'test',version:'1.1'}
Is there a way in Node.js to write well formatted JSON to file ?
JSON.stringify's third parameter defines white-space insertion for pretty-printing. It can be a string or a number (number of spaces). Node can write to your filesystem with fs. Example:
var fs = require('fs');
fs.writeFile('test.json', JSON.stringify({ a:1, b:2, c:3 }, null, 4));
/* test.json:
{
"a": 1,
"b": 2,
"c": 3,
}
*/
See the JSON.stringify() docs at MDN, Node fs docs
I think this might be useful... I love example code :)
var fs = require('fs');
var myData = {
name:'test',
version:'1.0'
}
var outputFilename = '/tmp/my.json';
fs.writeFile(outputFilename, JSON.stringify(myData, null, 4), function(err) {
if(err) {
console.log(err);
} else {
console.log("JSON saved to " + outputFilename);
}
});
If you just want to pretty print an object and not export it as valid JSON you can use console.dir().
It uses syntax-highlighting, smart indentation, removes quotes from keys and just makes the output as pretty as it gets.
const jsonString = `{"name":"John","color":"green",
"smoker":false,"id":7,"city":"Berlin"}`
const object = JSON.parse(jsonString)
console.dir(object, {depth: null, colors: true})
Under the hood it is a shortcut for console.log(util.inspect(…)).
The only difference is that it bypasses any custom inspect() function defined on an object.
If you don't want to store this anywhere, but just view the object for debugging purposes.
console.log(JSON.stringify(object, null, " "));
You can change the third parameter to adjust the indentation.
I know this is old question. But maybe this can help you 😀
JSON string
var jsonStr = '{ "bool": true, "number": 123, "string": "foo bar" }';
Pretty Print JSON
JSON.stringify(JSON.parse(jsonStr), null, 2);
Minify JSON
JSON.stringify(JSON.parse(jsonStr));
what about this?
console.table(object)
Another workaround would be to make use of prettier to format the JSON.
The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.
const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));
if prettify is name value pairs on new lines then specifying number of spaces in stringify didn't work for me the only thing that worked for me was
await fs.promises.writeFile('testdataattr.json',JSON.stringify(datatofile, null,'\r\n'),'utf8') ;