Unexpected token ILLEGAL : how to remove &quote; and lines breaks from JSON - javascript

I receive a jsonfrom the server when loading a page, and it gets populated in the page using Handelbars.java. Till now everything's fine.
However I would like to get that jsonobject and store it on a javascriptobject this is where I fail.
When I try to store it on a javascript object I do the following :
var jsObject = "{{output.items}}"; // the output.items is the JSON retrieved on the template
I get the following (&quote; and line breaks interpreted) :
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
....
}
When I should get the following (without line breaks interpreted) :
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
....
}
So it throws me an error on javascriptUncaught SyntaxError: Unexpected token ILLEGAL.
When printing the json on the HTML template using <pre>{{output}}</pre> it looks just fine.
Do you have any idea about how can I store the jsonreturned from the server on page loading on a javascriptobject as I don't have much control of it since it's NOT coming with json?
Thank you.

Your server is serving a incorrect json format.
Your server needs to serve a json string, with double quotes.
{
"profile": {
"name": "copernic",
"email": "copernic#cop.com"
}
}
If you need to serve a well-formed json, you can try with Gson.
https://sites.google.com/site/gson/gson-user-guide#TOC-Using-Gson

Since the content output.items ist a string, this is how you can proceed.
eval("jsObject={" + object.items.replace(/"/g,'"')+"}");

Related

How to turn a json string into a properly beautified string to be used in email using a Logic App

Logic App
"Send_an_email_(V2)": {
"inputs": {
"body": {
"Body": "<p><br></p>\n<pre><code>Message 1<br>\n<br>\n#{variables('Message1')}<br>\n<br>\nMessage 2<br>\n<br>\n#{variables('Message2')}</code></pre>\n<pre><code><br>\n<br>\n<br>\n<br>\n</code></pre>",
"Importance": "Normal",
"Subject": "Test",
"To": "test#test.com"
}
This is how it looks like in the email. I know the Message 2 has it already nicely formatted but I would want both to look the same.
Any ideas are appreciated.
After reproducing issue from my side, I got the expected results by taking Parse Json Action after initialize variable action.
As shown in below images i have taken initialize variable actions and send email.
With out parse Json action I got below output in email.
As shown in below image in Parse Json action take Content as Message 1 from dynamic content .
Schema :
{
"Request_Date": "2023-07-18",
"Number_of_Adults": "5",
"Number_of_Children": "1",
"Total_Cost": "690"
}
Then in Send Email action in body take your required data from dynamic content of parse Json 1 as shown in below image.
Then the logic App ran successfully and email got received with expected output format.
Reference MS document for parse Json.
replace(replace(replace(variables('Message1'),',',',<br> '),'{','{<br> '),'}','<br>}')

how to solve problem getting json object element

I have a json object that i want to use.
{
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjVkOTQ3OTg4N2RlMGRkMDc4ZjEzM2FmNyIsImVtYWlsIjoiYWxzb25nZHVuc3RhbjJAZ21haWwuY29tIiwicm9sZSI6IkNVU1RPTUVSIiwiaWF0IjoxNTcwMDI3MDA4fQ.FcpoBPmhTSX535bNgE2ezCCWsNFPjEhc87hM4y6WadM"
}
so when i try to access it using
console.log("Postback: " + payload.type)
but i get an error of
Postback: undefined
i have looked over some resources on the web and most of them do it this way and it works but i am not sure why mine is not giving the value for type
thanks in advance
Subh is right. You have to parse the JSON into an object before accessing type using payload.type syntax.
So, let's say you have the following:
let payload = {
"type": "PROVIDER_PAYLOAD",
"message": "eyJhbGciOiJIUzWadM"
}
You have to convert it into a JS object using JSON.parse:
let payloadObj = JSON.parse(payload);
Now, if you do payloadObj.type, you should be fine.
console.log(payloadObj.type); // PROVIDER_PAYLOAD
It should work fine.
UPDATE: ERROR: SyntaxError: Unexpected token a in JSON at position 0
If you are getting this error, try following to Parse the payload.
let payloadObj = JSON.parse(JSON.stringify(payload))
It should solve the problem for you.

Invalid JSON data with base64 string on Postman

I need to use Postman to send some JSON request. I have an issue here with base64 string. How can I format correctly as JSON property? Hope I have done wrong there.
Note: base64 string has more length. I have extracted part of it.
{
"api_key": "m40q-412u-99bd-388d-yazn",
"file_name": "fileName.pdf",
"file_content": "data:image/*;charset=utf-8;base64,JVBERi0xLjQKJe+/ve+/ve+/ve+/vQoxIDAgb2JqCjw8CiAgL1R5cGUgL0NhdGFsb2cKICAvUGFn
ZXMgMiAwIFIKPj4KZW5kb2JqCgoyIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2VzCiAgL01lZGlhQm94
IFsgMCAwIDI0ODAgMzUwOCBdCiAgL0NvdW50IDEKICAvS2lkcyBbIDMgMCBSIF0KPj4KZW5kb2Jq
CgozIDAgb2JqCjw8CiAgL1R5cGUgL1BhZ2UKICAvUGFyZW50IDIgMCBSCiAgL01lZGlhQm94IFsg
MCAwIDU5MyA4NDEgXQogIC9SZXNvdXJjZXMgPDwKICAgIC9Gb250IDw8CiAgICAgIC9GMSA0IDAg
UgogICAgPj4KICAgIC9YT2JqZWN0IDw8CiAgICAgIC9pbWcxIDYgMCBSCiAgICA+PgogID4+CiAg
L0NvbnRlbnRzIDUgMCBSCj4+CmVuZG9iagoKNCAwIG9iago8PAogIC9UeXBlIC9Gb250CiAgL1N1
YnR5cGUgL1R5cGUxCiAgL0Jhc2VGb250IC9UaW1lcy1Sb21hbgogIC9FbmNvZGluZyAvV2luQW5z
aUVuY29kaW5nCj4+CmVuZG9iagoKNSAwIG9iago8PAogIC9MZW5ndGggNjIKPj4Kc3RyZWFtCnEK
MSAwIDAgMSAwIDAgY20KMSAwIDAgMSAwIDAgY20KNTkyIDAgMCA4NDEgMCAwIGNtCi9pbWcxIERv
ClEKZW5kc3RyZWFtCmVuZG9iagoKNiAwIG9iago8PAogIC9MZW5ndGggMzQ3NDUKIC9UeXBlIC9Y
T2JqZWN0CiAvU3VidHlwZSAvSW1hZ2UKIC9GaWx0ZXIgL0RDVERlY29kZQogL1dpZHRoIDQyMwog"
}
My API shows this error:
{
"errors": [
{
"code": 400,
"detail": "Invalid JSON data."
}
]
}
The problem seems to be with the new line (carriage return), just copy this json and paste it in jsonlint.com you will get to know.
You can further refer this question for more details Multiline strings in JSON

Reading JSON data from JS file

I am uploading one JS file using HTML input file tag. I am reading the data in Python. Since in my data var acb_messages is written, I am not able to parse it. And I want to use this variable name to get the data so I can remove it.
var acb_messages = {"messages": [{
"timestamp": 1475565742761,
"datetime": "2016-10-04 12:52:22 GMT+05:30",
"number": "VM-449700",
"id": 1276,
"text": "Some text here",
"mms": false,
"sender": false
}
]}
How can I parse it in Python and then how can I use it?
Two approaches that I would try if I were at your place -
Convert my .js file to .json file and then using method suggested by #Sandeep Lade.
Reading .js file as string, cropping out the value part and then using json.loads(<cropped part>) as suggested by #rahul mr.
Here is how to achieve 2nd solution -
import json
with open('your_js_file.js') as dataFile:
data = dataFile.read()
obj = data[data.find('{') : data.rfind('}')+1]
jsonObj = json.loads(obj)
What's happening here is that you are finding first reading your .js file (that contains js object that needs to be converted into json) as string, find first occurence of { and last occurence of }, crop that part of string, load it as json.
Hope this is what you are looking for.
Warning - Code works only if your js file contains js object only.
The options above are correct, but the JSON syntax in JS can be a little different than in Python:
example.js:
property.docs = {
messages: {
timestamp: 1475565742761,
datetime: "2016-10-04 12:52:22 GMT+05:30",
number: "VM-449700",
id: 1276,
text: "Some text here",
mms: false,
sender: false
}
};
Therefore we need one more tweak that I found at: How to convert raw javascript object to python dictionary?
The complete code should be:
import json
import demjson
with open('example.js') as dataFile:
data = dataFile.read()
json_out = data[data.find('{'): data.rfind('}')+1]
json_decode = demjson.decode(json_out)
print(json_decode)
import json
jsonfile=open("/path/to/json file")
data=json.load(jsonfile)
the above code will store will store your json data in a dictionary called data. You can then process the dictionary

$scope.someVariable can't be touched

I'm new to AngularJS so my mistake might be anywhere in my code and I can't find it. I'm using $HTTP GET method to retrieve data that's located in some server /page. After retrieving that data (which is JSON) I want to play with that string to retrieve the data properly, like name: number: and so on. But the thing is once I put that data into $scope.listOfCompanyUsers I can't touch it. If I try to $scope.listOfCompanyUsers.slice(..) or if I try any other string function on that object my entire webpage crashes. I "alert()"'d the $scope.listOfCompanyUsers and the result is:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
What I wanted to do is remove the pre and br tags from that string so I have a pure JSON string that I could play with but again any function I try on $scope.listOfCompanyUsers crashes my site. What do I do? I tried var someOtherVariable = $scope.listOfCompanyUsers but that variable doesn't work later. I'm adding parts of my code because my mistake might be somewhere else.
Controller:
$http({
method: 'GET',
url: '/someURL'
}).then(function successCallback(response) {
$scope.listOfCompanyUsers = response.data;
},
function errorCallback(response) {
alert(response.status);
});
Later on the same controller:
.
.
$scope.someFunction = function () {
.
.
else {
alert("Maximum of 9 other passengers!");
alert($scope.listOfCompanyUsers);
// In this alert I could see the $scope.listOfCompanyUsers as mentioned above
}
};
My target right now is to have a var objectOfUsers = [{admin: true, id:123, username: "name", last_name: "test", name: "something"}, {next user.}, .] but because I can't touch the $scope.listOfCompanyUsers I'm stuck.
The problem is that the server is adding some extra tags to the response that shouldn't be in there:
<pre>[
{
"admin": true,
"id": 123,
"username": "someName",
"last_name": "someLastName",
"name": "John Doe"
}
]</pre><br>
Edit your server-side code, to remove: <pre> and </pre><br>.
Then the call will work.
Is your response a string? If your response has HTML tags, then that is not valid JS object format. It looks like you have a Javascript array with one object, enclosed by some HTML tags.
Therefore you won't be able to access anything within this using the object reference notation (.) until you treat it like a string and use String.prototype.replace and replace the tags, and then do a JSON.parse on the remaining string to convert it into an object
Very strange server response, so possible solutions are:
Change server response to standard JSON without unwanted <pre>
If You can not change response remove not wanted part of response using regular expression in JS. Working example how do that:
var response='<pre>[{"admin": true, "id": 123, "username": "someName","last_name": "someLastName", "name": "John Doe"}]</pre><br>';
var goodResponse=response.match(/>([^<]*)</)[1];//remove not wanted signs
var parsedGoodResonse=JSON.parse(goodResponse);
console.log(parsedGoodResonse);//here we have parse js array
In parsedGoodResonse You have object which can be "touched" so exactly what You need.
The problem with the extra tags is not on your code, it's on the server-side. You should check the code on the server and find the reason for those extra tags. They can't be there because they are making the response an invalid JSON.

Categories