I have a function in AWS Lambda in which I retrieve an unparsed JSON object, I parse it, and then access its values.
if(data.Payload){
var parsedData = JSON.parse(data.Payload)
console.log("PAYLOAD --> " + parsedData);
console.log("GROUPNAME --> " + parseData.groupName);
...
When I log to the console the parsedData variable, it seems like the parsing was successful:
PAYLOAD --> {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
The issue arises when I try to access the fields in the JSON as I keep getting undefined:
GROUPNAME --> undefined
NOTE:
If I copy and paste the JSON object
{"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
into a variable on the Chrome debugging console
var parsedData = {"groupName":"Hello!","membersCount":1,"searchField":"hello!"}
I am able to access the properties of the object as I am trying to do in the AWS Lambda function.
parsedData.groupName prints "Hello!"
Edit - temporary solution
The parsedData variable contains a String with a JSON, so the JSON object inside the "" I am not quite sure why. The temporary fix was to double parse the variable but that just seems wrong.
if(data.Payload){
var parsedData = JSON.parse(data.Payload);
var doubleParsed = JSON.parse(parsedData);
if(doubleParsed.groupName !== undefined) {
console.log(doubleParsed.groupName);
}
}
If that is a copy paste of your code, in your 2nd console.log you are using parseData NOT parsedData missing a D.
EDIT Just adding as answer what I wrote in comments.
It seems parsedData was not being parsed correctly, for some reason JSON.parse is not working, I think some information about data.Payload is needed to know what it exactly returns.
Yet the next code seems to solve it, but I would honestly need further explanation as why it needs to be done twice:
var parsedData = JSON.parse(JSON.parse(data.Payload));
Related
I was trying to use the method found here (see most up-voted answer):
Google Apps Script Fastest way to find a row?
I currently use this while it does work I wanted to try the above linked method yet when I replace the below code
function AutoPopulate (evalue)
{
//uses google drive file irretator reads in JSON file and parses it to a Javascript object that we can work with
var iter = DriveApp.getFilesByName("units.json");
// iterate through all the files named units.json
while (iter.hasNext()) {
// define a File object variable and set the Media Tyep
var file = iter.next();
var jsonFile = file.getBlob().getDataAsString();
// log the contents of the file
//Logger.log(jsonFile);
}
var UnitDatabase = JSON.parse(jsonFile);
//Logger.log(UnitDatabase);
//Logger.log(UnitDatabase[1027]);
return UnitDatabase[evalue];
}
WITH THIS CODE:
function AutoPopulate (evalue)
{
//this method did not work for me but should have according to stackflow answer linked above I am trying to understand why or how I can find out why it may have thrown an error
var jsonFile = DriveApp.getFilesByName("units.json").next(),
UnitDatabase = UnitDatabase.getBlob().getDataAsString();
return UnitDatabase[evalue];
}
I get an error in the excecution indicating that there is a % at postion 0 in the JSON, between the methods I dont alter the JSON file in anyway so I dont understand why does the top method work but the bottom one does not?
For further information the idea behind the code is that I have a list of Unit numbers and model numbers that are in a spreadsheet. I then convert this to a JSON file, this however is only done when a new unit is added to the fleet. As I learned one can parse a whole JSON file into a javascript object which makes working with the data set much faster. This javascript object is used so that when a user enters a UNIT# the MODEL# is auto populated based on the JSON file.
I cannot share the JSON file as it contains client information.
Your code does not work for two reasons:
You have a typo in the line UnitDatabase = UnitDatabase.getBlob()... - it should be UnitDatabase = jsonFile.getBlob()...
If you want to retrieve a nested object from a json file - you need to parse the JSOn - otherwise it is considered a string and you can not access the nested structure
Modified working code:
function AutoPopulate2 (evalue)
{
var jsonFile = DriveApp.getFilesByName("units.json").next();
var UnitDatabase = JSON.parse(jsonFile.getBlob().getDataAsString());
return UnitDatabase[evalue];
}
Mind that this code will only work if you have a "units.json" file on your drive and if evalue is a valid 1st-level nested object of this json.
the code in Script (FB setup is already done)
var base = FirebaseApp.getDatabaseByUrl(firebaseUrl,secret);
var data = base.getData();
var rowNum = 1;
var range = Sheet.getRange("A"+rowNum+":DH"+rowNum+"");
for (i in data) {
Logger.log(data[i]);
range.setValues(JSON.parse(data[i]))
rowNum += 1;
range = Sheet.getRange("A"+rowNum+":DH"+rowNum+"");
}
the Logger shows the the 112 elements from Firebase just fine, but I can't get the data parsed correctly. the JSON.parse fails saying "Cannot find method setValues(object)".
The message "Cannot find method setValues(object)" is related to range.setValues() method. It means that JSON.parse() works as expected and returns JSON object, but setValues() argument must be 2D array, not JSON object.
You should convert JSON object to array before using as argument. See an example. In general case, the convertion code depends on the object structure, so we can not write the exact code here. It may appear rather long for 112 elements... But we can append it here after you give more details.
I am doing an Ionic App with typescript.
I have some error condition as response from REST API,
I did
err._body
and it gives me
{"reason":"invalid_token"}
but when I do
err._body.reason
or
err._body.get("reason")
it gives undefined value.
I did JSON stringify and parse as well, no luck,
How to parse this and get the value so that I can apply specific processing for this.
First try to do
console.log(typeof err._body);
so we can be sure what the type of that is. If it's a string, you should do
let errorObj = JSON.parse(err._body);
// And then...
let errorMsg = errorObj.reason // or errorObj["reason"] as well
If it's an Object, you can skip the parse() part and just use it like this:
let errorMsg = err._body.reason // or err._body["reason"]
I don't know if I'm going crazy here but I'm doing something very basic that would usually be trivial, but I've been stuck on it for awhile now.
I'm receiving a message from a client like so:
socket.on('request_username', function(messageFromClient) {
if(messageFromClient == undefined) {
Logger.logError("messageFromClient was undefined in socket_api.js");
return;
}
// Parse the message into Json, might not be needed.
// Logs: "{\"username\":\"test\"}"
console.log(messageFromClient);
try {
messageFromClient = JSON.parse(messageFromClient);
//Logs: {"username":"test"}
console.log(messageFromClient);
} catch(err) {
console.log("Error parsing json from request_username. Mesage is %s", err);
return;
}
// All undefined.
console.log(messageFromClient['"username"']);
console.log(messageFromClient["username"]);
console.log(messageFromClient['username']);
// msg == undefined incase the parse failed.
if(messageFromClient == undefined || messageFromClient.username == undefined) {
Logger.logError("messageFromClient.username was undefined in socket_api.js");
return;
}
var usernameRequested = messageFromClient.username;
Now I'm getting this in the logs
"{\"username\":\"test\"}"
{"username":"test"}
Log Error: messageFromClient.username was undefined in socket_api.js
I've no idea what I'm doing wrong..
With socket.io, it automatically serializes Javascript data to/from JSON. You do not have to do that and if you attempt to, you can mess things up.
In socket.io, you can send like this:
var data = {username: "test"};
socket.emit('request_username', data);
Then, on the receiving side, you would have:
socket.on('request_username', function(data) {
console.log(data.username); // will show "test"
});
The serializing to/from JSON is done automatically by the socket.io library (one of its many useful features).
To debug your particular situation further, we will need to know exactly what the very first console.log(messageFromClient) shows right when the message first arrives before you've done anything to it?
You show a bunch of log info, but it's not entirely clear which debug line corresponds with which line of code. If that very first console.log shows:
"{\"username\":\"test\"}"
then your message is apparently still JSON which is probably because it was doubly JSON encoded which is an error on the sending side. This should be fixed on the sending side rather than trying to double parse it.
Also, when discussing this problem please be aware that JSON is a string format. A Javascript object is something you can directly access properties on in Javascript code. It appears you are sometimes calling them both JSON which is confusing for all. You convert a Javascript object to JSON with var jsonStr = JSON.stringify(obj) and you convert JSON to a Javascript object with var obj = JSON.parse(someJSON).
var obj = {username: test}; // Javascript object
var jsonStr = JSON.stringify(obj); // produces a JSON string
var obj2 = JSON.parse(jsonStr); // parses JSON string back to a Javascript object
I want to store the result from a call to a Domino Access Service (DAS) in a localStorage however when I try to convert the result object to a JSON string I get an error.
With DAS you get the result as an Array e.g.:
[
{
"#entryid":"1-CD90722966A36D758025725800726168",
"#noteid":"16B46",
Does anyone know how I get rid of the square brackets or convert the Array quickly to a JSON object?
Here is a snippet of my code:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
localStorage.setItem('myCatalog',JSON.stringify(data));
}
});
Brackets are part of the JSON syntax. They indicate that this is an array of objects. And as you point to a view it is very likely that you would get more than one object back (one for each entry in the view).
So if you are only interested in the first element you could do this:
var REST = "./myREST.xsp/notesView";
$.getJSON(REST,function(data){
if(localStorage){
var firstRecord = data[0] || {};
localStorage.setItem('myCatalog',JSON.stringify(firstRecord));
}
});
Otherwise, you would need to define a loop to handle each of the objects :-)
/John