please help, i know its something easy but cant figure it out.
I have a Json Response that comes back looking like this
onSmData({"valid":true,"token":"201777121"});
on my javascript i try to read the response like this
console.log(data[0].valid);
console.log(data[1].token);
but i keep getting this error.
Uncaught TypeError: Cannot read property 'valid' of undefined
What am I doing wrong?
Try data.token and data.valid?
I believe first of all you need to parse the json value. For example:
var jsonObject = JSON.parse(response);
and only then try to get the values like you do from the parsed object - this example case jsonObject.
The Following example will make it clear:
var jsontext = '{"name":"x","age":"11"}';
var getContact = JSON.parse(jsontext);
document.write(getContact.name + ", " + getContact.age);
// Output: x, 11
Data doesn't seems to be an Array. I guess this should work :
console.log(data.valid);
console.log(data.token);
To be sure, juste log :
console.log(data);
Related
I am trying to get form data to json object and modify it... But it is not working...
Here is my code-
let formData = new FormData(thisForm).entries();
let body = JSON.stringify(Object.fromEntries(formData));
console.log(body);
console.log(body.firstName);
console.log("service=" + body.service);
body.service = "hello";
the console.log(body) is printing output like this-
{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}
But console.log(body.firstName); is printing undefined.
Same thing is happening for other things.. What is the problem?
It's because body is a string, not a JSON object, because you've JSON.stringify'd it.
Use JSON.parse instead to create a JSON object that you can edit like that.
var body = '{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}';
var jsonBody = JSON.parse(body);
console.log(jsonBody.firstName);
Because you use JSON.stringify() on the object first.
You use that to transfer the object over http. Apply that later on and you're fine.
I'm trying to pass python dictionaries and javascript objects back and forth as necessary. From similar questions, I've gathered that I need to do this.
Python:
posts = [
{'author':'JL Rowling','title':'Harry Potter'},
{'author':'JRR Tolkien','title':'Lord of the Rings'},
]
Javascript:
var jsonPosts = JSON.parse({{ posts }});
console.log(jsonPosts);
Likewise, these doesn't work either:
var jsonPosts = JSON.parse(posts|tojson);
var jsonPosts = {{ posts|tojson }};
The JS error I'm triggering is TypeError: Object of type Undefined is not JSON serializable
I got this advice from the following Q/A:
Python to Javascript JSON objects (Flask)
How can I pass data from Flask to JavaScript in a template?
How can I fix this?
Edit:
I've used answer recommendation and found the following error to be present in the console:
VM129:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0
at JSON.parse (<anonymous>)
at about:16
Corresponding to
let jsonPosts = JSON.parse();
It seems that it doesn't have access to encoded_posts.
You need to use the encoded posts:
encoded_posts = json.dumps(posts)
That will give you string, which is what JSON.parse is expecting.
var jsonPosts = JSON.parse({{ encoded_posts }});
I have a JSON object in backend which I want to send to frontend javascript. But I'm constantly encountering "undefined" when trying to access that variable.
candidates is json object and is working fine in server side.
Here's my server side code.
res.render('electionview',{title: 'Election', poll: poll, data: JSON.stringify(candidates) });
Here's my script in Handlebars
<script type="text/javascript">
var candidates = {{{data}}};
console.log(candidates);
<script>
But I'm getting this error in console.
Uncaught SyntaxError: Unexpected token ';'
When I remove semicolon, output in the console is undefined. What am I missing ?
Server-side:
let obj = {};
obj.title = 'Election';
obj.poll = poll;
obj.data = candidates;
res.render('electionview', obj);
I'm assuming that the render function already knows how to serve objects as JSON, so no need to JSON.stringify anything.
Then, on the client-side, JSON.parse() the object above in whole. After that, it should have a data property that you can use as needed.
I was getting candidates as:
Candidate.find({}).lean()
.then(candidates=>res.render("electionview", JSON.stringify(candidates))
Removing .lean() fixed it.
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.
I'm trying to retrieve the JSON data given below but I'm unable to.
Since I'm using Javascript Ajax success function, when I try doing alerts with the code,
$.ajax({
type:'GET',
url:myURL,
success : function(data) {
alert(data);
//{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
}
});
I am retrieving the below JSON data.
{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}
But when I try trying to get the value of mainIsActive using:
alert(data.object1.mainIsActive);
I am getting the error in the console:
"Cannot read property 'mainIsActive' of undefined at Object.success (:143:30)"
Can you please help? I also attached the JSON image so you can understand the structure better.
The JSON data will be available in object structure once you have parsed it using
JSON.parse(StringYouWantToParse)
This code seems to work properly:
var x = '{"object1":{"mainIsActive":"A","mainBuildingGL":"01493","mainIsUnderCons":"B"},"object2":[[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],[{"statLabel":"Cafeteria","statCount":"1"},{"statLabel":"Restaurant","statCount":"2"}],{"newBuildingGL":"15450"}]}';
var data = JSON.parse(x);
alert(data.object1.mainIsActive);