I am trying to parse a JSON object in Google Scripts but I can't seem to get it to work.
The JSON I am trying to parse looks like this
{
"keywords":[
{
"c":0.015165274822976534,
"monthly":[ ],
"kw":"handstand",
"n":60500,
"sb":0.3
}
],
"not_found":[
]
}
I can't seem to access any of the values within the object. If I use JSON.parse() it seems to create a non-JSON object.
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj);
Returns
{keywords=[{c=0.015165274822976534, monthly=[], kw=handstand, n=60500, sb=0.3}], not_found=[]}
This doesn't validate.
If I try to work with that anyways this happens
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[
],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
var obj = JSON.parse(response);
Logger.log(obj.keywords.n)
Returns undefined
If I don't use JSON.parse and just work with the original response object I get the following:
var response = '{"keywords":[{"c":0.015165274822976534,"monthly":[ ],"kw":"handstand","n":60500,"sb":0.3}],"not_found":[]}'
Logger.log(response.keywords);
I get undefined
I'm not really sure where I am going wrong here. Any help is appreciated. Thanks!
As #Tanaike mentions, your n property is a property of an object in the keywords array. So to log the values of n, you need to - after parsing the string to JSON - evaluate each object in keywords:
var response = '{"keywords":[{"c": 0.015165274822976534, "monthly": [ ], "kw": "handstand", "n": 60500, "sb": 0.3}], "not_found": []}'
var obj = JSON.parse(response);
// Log all values of n for each keyword:
obj.keywords.forEach(function (keyword) {
console.log("Word: " + keyword.kw + ", times used: " + keyword.n);
});
Related
It is pretty straight forward to to get a value of a key from json response in postman say :
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData.value);
});
For JSON Response
{
"value": "task-1405"
}
I am not able to extract json value in the below case where key has a '.' as part of its string.Can any one help me with this.
"result": {
"cluster.moid": "domain-c433242"
}
I tried the following below code:
pm.test("abc", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var moid = result.'cluster.moid' ;
pm.environment.set("clusterMoid", moid);
});
Could figure out to extract value for the above case, The below code works
pm.test("StatusForAddClusterApplyCheck", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var jsonString = JSON.stringify(result).substring(17,31);
pm.environment.set("clusterMoid", jsonString);
});
But only if the string length are constants.
Any other answer in case string length are dynamic?
In javascript (And also in postman), object properties can be accessed with '.' operator or with associative array indexing using []. The same goes for JSON objects.
ie. object.key is equivalent to object["key"].
this should do the trick for you:
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData["cluster.moid"]);
});
I have the following JSON
{
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
}
Using
var jsonObj:Object = JSON.parse(str);
Gives the error:
SyntaxError: Error #1132: Invalid JSON parse input.
at JSON$/parseCore()
at JSON$/parse()
I do not understand why this is, the JSON is valid.
Additional information,
The solution I have tried and works is as follows, despite the before and after been valid.
var clean:String = str.split("\\").join('');
clean = clean.replace('"custom":"{"a"', '"custom":{"a"');
clean = clean.replace('"}","from"', '"},"from"');
Few observations :
The JSON provide in OP is looking like a JSON object instead of JSON string.Hence, No need to parse the whole object.
As partialJsonObj.extras.custom is a JSON string parse it to convert into JSON Object.
DEMO
var partialJsonObj = {
"extras": {
"google.sent_time": 1502027522898,
"custom": "{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}",
"from": "62572096498",
"alert": "Read More...",
"title": "New message",
"google.message_id": "0:2905559%2ecccafd7ecd"
}
};
partialJsonObj.extras.custom = JSON.parse(partialJsonObj.extras.custom);
var jsonObj:Object = partialJsonObj;
console.log(jsonObj);
If this "JSON" is part of your actionscript it's an Object, not a JSON.
The JSON.parse method won't work because accepts JSON-formatted String as first parameter and you pass and Object instead.
If you load/import this script from a JSON file, the JSON.parse method will work.
// importing the external JSON file
function loadJSON() {
var loader:URLLoader = new URLLoader();
loader.addEventListener(Event.COMPLETE, decodeJSON);
loader.load(new URLRequest("test.json"));
}
// converting to actionscript Object
function decodeJSON(e:Event):void {
var loader:URLLoader = URLLoader(e.target) ;
var jsonObj:Object = JSON.parse(loader.data);
trace(jsonObj["extras"]["custom"]["a"]["message_id"]);
}
loadJSON();
If you want to access the "custom" value, uncomment double quotes in the JSON file:
"custom": {"a":{"message_data":"","message_id":"749","message_command":"MESSAGE"},"i":"899ec3dd"},
I believe str is a javascript object already, so nothing to parse and you can simply assign it like:
var jsonObj:Object = str;
However I'd assume you need to parse and convert to object your custom property:
a.extras.custom = JSON.parse("{\"a\":{\"message_data\":\"\",\"message_id\":\"749\",\"message_command\":\"MESSAGE\"},\"i\":\"899ec3dd\"}")
I am pretty new to JSON / Jquery world so please bear with my ignorance.
I am trying to read an output from a Json data returned by webservice call like below :
My webservice call is here:
http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297
This return the data as :
{
"data": [
{
"PORTFOLIO_ID": 13495,
"SUBSCRIPTION_ID": 1653,
"STATUS": "ACTIVE",
}
],
"success": true
}
Now I am trying to get alert onthe Json Data returned as string and also want to get this as Parsed /
<script>
var parsed ;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(data);
alert(parsed) ;
</script>
I am getting the response in Alert as "Undefined" . I may not be doing right handling the success handler . I want to get each value and specific value of the json data returned.
Please help.
Thanks
I am getting the response in Alert as "Undefined".
Reason : You are trying to parse the API response out of the scope. As data object is only accessible in the promise returned by the API call.
Try this hope it will work as per your expectation :
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(res) {
var data = res.data;
alert(JSON.stringify(data));
});
You are calling data out side the scope.
<script>
var parsed ;
var myData;
$.getJSON("http://example.com/getPortfolioListByContact.json?component=C1&contactId=510297", function(data){
myData = data;
alert(data.SUBSCRIPTION_ID);
});
parsed = JSON.parse(myData);
alert(parsed) ;
</script>
Question is simple, but not answered perfectly yet for me (perhaps only for me but is not totaly clear..)
Question : I want to return MongoDB from "collection.findOne" with mongo.. is ok AND JSON.stringify() this informations for send to another service...
// i past a pseudo code for response :-)
collection.find({id_to_find: id_to_find}, function(err, results) {
if (err){
console.log ("error find");
}if (results) { // update for good syntax !
var results = JSON.stringify(results); // error, why ??? <if not this line, is ok, but i want stringify !>
res.json({
returnJSON: results
});
}
}
////////////////////////////////////
// example of a mongo object return :
[ { _id: 1,
property: 'xxxx',
etc: 'xx'
},
{ _id: 2
property: 'xxxx',
etc: 'xxxx'
}
]
Next time, i have severals records like
results_mongo = [{mongo object datas},{ etc.. }] // like an array
i want with my server node.js to JSON.stringify my collection && return theses results..
The error is :::::
TypeError: Converting circular structure to JSON
at Object.stringify (native)
Response ?
(thank to correct object to result, my question is how to exept the stringify deep object.. :)
for searchs, a goods posts on stack :
Convert Mongoose docs to json
How do you turn a Mongoose document into a plain object?
// you are passing object to your stringify method.
var object = JSON.stringify(object);
// you need to pass results as your callack method returns results
var object = JSON.stringify(results);
I am trying to create a webservice using the Contentservice in Apps Script and doPost(e) function to interact with Google Apps AdminDirectory service
Here is the overview of my code. I saved this as my server and published it as a websapp
function doPost(e) {
var data = e.parameter;
var resourceType = data.resourceType;
var method = data.method;
var resource = data.resource;
var resourceParams = resource.parameters;
//other code to work with AdminDIrectory
// return ContentService.createTextOutput(myoutputdata).setMimeType(ContentService.MimeType.JSON);
}
In my client code which I wrote using Apps Script to test the webservice
function test() {
var jsonData = {
authKey : 'HwZMVe3ZCGuPOhTSmdcfOqsl12345678',
resourceType : 'user',
method : 'get',
resource : {
parameters : {
userKey : 'waqar.ahmad#mydomain.com'
}
}
}
var url = 'https://script.google.com/macros/s/xyzabc12345678_wE3CQV06APje6497dyI7Hh-mQMUFM0pYDrk/exec';
var params = {
method : 'POST',
payload : jsonData
}
var resp = UrlFetchApp.fetch(url, params).getContentText();
Logger.log(resp);
}
Now when I try to read e.parameter.resource.parameters on server side, it gives error and shows that e.parameter.resource is string type.
How I can read nested objects on server side? It seems, it is recognizing only first level parameters.
Using
function doPost(e) {
return ContentService.createTextOutput(JSON.stringify(e.parameter)).setMimeType(ContentService.MimeType.JSON);
You get the response
"{"authKey":"HwZMVe3ZCGuPOhTSmdcfOqsl12345678","resource":"{parameters={userKey=waqar.ahmad#mydomain.com}}","method":"get","resourceType":"user"}"
so it looks like it is flattening any nests into a string. In the comments of a similar problem it is noted that the documentation for UrlFetchApp permits the payload to be "It can be a String, a byte array, or a JavaScript key/value map", but I assume this doesn't extend to nested key/value maps.
As noted in the other answer the solution would be to stringify the payload e.g.
var params = {
method : 'POST',
payload : {'data':JSON.stringify(jsonData)}
};
I had problems handling the payload just as a string which is why I used a key value
On the server side script you can handle with
function doPost(e) {
var data = JSON.parse(e.parameter.data);
var userKey = data.resource.parameters.userKey;
...
}
Maybe it arrives as JSON string? If that's the case you'd have to parse it back-end, something like:
resourceObj = JSON_PARSE_METHOD(e.parameter.resource);
for example in PHP this would be
$resourceObj = json_decode(e->parameter->resource);
You could find out if it's a JSON string by printing its value (or debugging it) on the backend.
Hope this helps. Cheers