JSON object array return undefined - javascript

I have below scripts on Google Apps Script which will take in an JSON event.
I want the data in element "events", but it always return "Undefined" to me.
I'm guessing maybe it's because events is a JSON array and I can't directly use it in JS?
Here is my code:
function doPost(e) {
var msg = JSON.parse(JSON.stringify(e.postData.contents));
console.log(msg);
//log succesfully
console.log(msg.events);
//"Undefined"
}
If I try to log the elements in the events instead of the array events itself:
console.log(msg.events[0].replyToken);
//"TypeError: Cannot read property '0' of undefined at doPost(app:26:25)"
The result of msg will is in below:
{
"destination": "U656de3c6b48c8e0d44edda4fd3f05e06",
"events": [
{
"type": "message",
"message": {
"type": "text",
"id": "*********",
"text": "Hi"
},
"timestamp": 1642616050062,
"source": {
"type": "group",
"groupId": "***********",
"userId": "*************"
},
"replyToken": "************",
"mode": "active"
}
]
}
I've seen several similar problems for array in JS.
I tried them but all of them didn't work, please help me.

I guess the result your getting from your API as e.postData.contents is a JSON string.
In this case something like this:
var msg = JSON.parse(JSON.stringify(e.postData.contents));
would first try to turn something into a JSON string (JSON.stringify) and then converting it into a JavaScript object by JSON.parse. In other words the JSON.stringify is useless.
Try this instead:
var msg = JSON.parse(e.postData.contents);

If the value from "e.postData.contents" is already a string, you don't have to do JSON.stringify.
If you do JSON.parse(JSON.stringify(any string) it results in adding backslash" to the values. For example
let str = '{name: "John"}';
let myJSON = JSON.stringify(str);
myJSON = "{name: "John"}"
So, please make sure "e.postData.contents" is not a string.

Related

Json Merge an id to a url

Good morning everybody,
i'm working on a Slack Workflow and i exported the .json file to work on it manually.
In a step of the workflow, it opens a ticket on Jira and returns the Issue Key with this form:
"id": "d9332296-a027-4b51-a52b-d8d69f131374==issueKey"
I need to automatically add that ID to an url, i tried to pass it through % encoding but it doesn't work.
This is the code related to the specific action:
[
{
"id": "**d9332296-a027-4b51-a52b-d8d69f131374==issueKey**",
"type": "workflowtoken",
"property": "",
"data_type": "text"
},
{
"text": "\n\nLink to the issue: ",
"type": "text"
},
{
"url": "https://test.slack.com/channels/**%7B%7Bd9332296-a027-4b51-a52b-d8d69f131374%3D%3DissueKey%7D%7D**",
"text": "LINK",
"type": "link"
}
]
Do you know any easy way to store the value and pass it (like concatenate it with the url) or any other valid way to reach my goal?
Thank you very much,
P.
I tried to pass a json ID through % encoding to the url but it doesn't work.
Its hard to understand the context but the simplest way is to define some placeholder like JIRA_ISSUE_KEY and then replace it on every property that should get this issue key.
const dataObject = {
"id": "**d9332296-a027-4b51-a52b-d8d69f131374==JIRA_ISSUE_KEY",
"type": "workflowtoken",
"property": "",
"data_type": "text"
}
const injectVariables = (data, property, value) => {
const result = JSON.parse(JSON.stringify(data)); // silly copy
for(const key of Object.keys(result)){
if(result.hasOwnProperty(key)){
result[key] = result[key].replace(property, value);
}
}
return result;
};
const injectedData = injectVariables(dataObject, 'JIRA_ISSUE_KEY', 'project-123');
console.log(injectedData);

How to convert JSON property array to Array of strings Object in node.js?

I currently have the following JSON:
{
"Id": ["1", "2"],
"Settings": [{ "Key": "IgnitionOn", "Value": "true" }]
}
I want to be able to access Id and convert it to an Array of strings in node.js. Namely, what I want to do is access Id using req.body.Id. This works when Id is just a string. If I try to access req.body.Id currently, I get it to be undefined. I have also tried JSON.parse(req.body.Id) and JSON.stringify(req.body.Id) but in both approaches, the Ids are still undefined. Given my req body above, any suggestions on how I can create an instance of an array that is precisely the Id array in the body?
Any help will be much appreciated!
You can parse this JSON to get an object:
const result = JSON.pasrse(req.body)
const id = result.id;
If you body is in JSON, you will need to parse then entire body with JSON.parse(req.body) before accessing the .Id field
let req = {
body: `{
"Id": ["1","2"],
"Settings": [{"Key": "IgnitionOn", "Value": "true"}]
}`
}
let body = JSON.parse(req.body)
let ids = body.Id
console.log(ids)
// [ '1', '2' ]

Object to Array returns undefined

Im trying to convert JS Object to an Array but Array after conversion is undefined.
I initially have JSON but from what I have read it is automatically parsed into JS Object (when I try to parse it, I get SyntaxError: Unexpected token o in JSON at position 1). Also when I console.log(typeof cityList) I get Object.
Initial JSON goes like this:
[
{
"id": 707860,
"name": "Hurzuf",
"country": "UA",
"coord": {
"lon": 34.283333,
"lat": 44.549999
}
},
{
"id": 519188,
"name": "Novinki",
"country": "RU",
"coord": {
"lon": 37.666668,
"lat": 55.683334
}
}
]
I import JSON like this: import cityList from './city.list.json';
I use this code to convert:
const cityListArray = Object.values(cityList);
If I console.log(cityListArray) I get undefined.
I also tried: const cityListArray = Object.keys(cityList).map(i => cityList[i]) but result is the same.
Im not sure where the problem is. Any help would be appreciated!
You don't need to convert anything, since the JSON object is already an array.
You shouldn't check if something is an array with typeof since it returns "object" for arrays.
const a = [];
typeof a; // "object"
You should use the Array.isArray() method instead.

Parsing a JSON object-within-an-object in javascript

I have a JSON object that looks like this:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [ {... // contains lots objects with the data I'd like to access } ]
As noted above, I want to access the product array of objects. I can't seem to do this though. I've tried:
console.log(json['cj-api']['products'][0]['product']);
But I get typeError: Cannot read property 'products' of undefined.
What's the correct way to access the array of product (note, singular product, not products). This data is coming from an external source so I can't alter the hyphen in cj-api.
EDIT: Here's what the raw console log of json looks like:
{"cj-api":{"products":[{"$":{"total-matched":"231746","records-returned":"999","page-number":"1"},"product":[{ << lots of data in here>>
EDIT 2: To further clarify, I got this object by running JSON.stringify(result) after I put some XML into XML2js.
i have tried the following JSON structure:
var json = {
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": [
{
"a": "a",
"b": "b",
"c": "c"
}
]
}
]
}
};
with the log statement as:
console.log(json['cj-api']['products'][0]['product']);
And result is as follows:
[Object { a="a", b="b", c="c"}]
Well your way of accessing json is absolutely correct. This is for debugging. Try
console.log(json['cj-api']);
console.log(json['cj-api']['products']);
console.log(json['cj-api']['products'][0]);
console.log(json['cj-api']['products'][0]['product']);
Which ever line returns undefined means your json is broken there.
If this doesn't work then you need to check for other similar keys. Maybe they value you are trying to find is actually undefined.
Maybe you are trying to loop. If you are then check for the condition if (JSONStructure[key]==undefined) console.log("Undefined at position ..."). That is the only way if you have valid JSON.
typeError: Cannot read property 'products' of undefined means that json exists, but json['cj-api'] is undefined. If you are sure that you are using the right variable name, I think this might be a scope issue, where you are using an other variable than you intend to. json might be the json string, instead of the array-like object. Try renaming your variable and see if you still get this problem. Otherwise the string is not automatically parsed for you and you'll have to parse it with JSON.parse( ... ).
Edit:
var json = '{ "me": "be an evil string" }';
console.log( json ); //'{ "me": "be an evil string" }'
console.log( json['me'] ); //undefined
console.log( JSON.parse( json )['me'] ); // 'be an evil string'
Since your question is missing the last
}
]
}
}
and others here changed your example and made it work, did you try to correct it?
If not then I suggest you or the dataprovider correct the structure of the reply.
I have tried below json structure
var json={
"cj-api": {
"products": [
{
"$": {
"total-matched": "231746",
"records-returned": "999",
"page-number": "1"
},
"product": []
}
]
}
}
now json['cj-api']['products'][0]['product'] will work

json comes in as object not string

Json is sitting on my localhost as: /data/:
{
"children": [
{
"name": "analytics",
"size": "1243"
},
{
"name": "math",
"size": "4343"
},
{
"name": "algebra",
"size": "1936"
},
{
"name": "calc",
"size": "3936"
},
{
"name": "geom",
"size": "2136"
},
{
"name": "Quant",
"size": "4136"
}
]
}
Here is how I am trying to access the json:
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,name){
alert(json.children);
});
});
}, 3000);
The data comes in just fine. That is, when I run console.log(json) I can see the above json name/value txt pairs in firebug. However, before each name value pair I see the word Object. So for example instead of my log showing { name="analytics", size="1243"},.. it actually shows: [Object { name="analytics", size="1243"},... And that too is what my alert shows: [object Object] instead of name="analytics", size="1243".
Why is this and is there a way to get my json name/value pairs in text so that I can store as a javascript String?
Many thanks in advance.
jQuery does automatically decode the response when using jQuery.getJSON or specifying the response as JSON. If you want the plain response, use jQuery.ajax instead.
The O in JSON stands for "object." It's a way of serializing a JavaScript object to a string (and back). You seem to be relying on the conversion on one hand (referencing children) but not want to have the conversion done on the other hand. If you really want children to be a collection of strings in the format you describe, you should store it that way. If you really do want the object notation (and conversion to objects in the client), then you can simply use the properties of the object.
var interval = setInterval(function() {
$.getJSON("http://localhost:8080/dev_tests/d3/examples/data/flare2.json", function(json) {
$.each(json.children,function(i,item){
alert("name = " + item.name + ", size = " + item.size);
});
});
}, 3000);
Everything you've stated is normal behavior for both firebug and alert. You can't alert an object.
Here's example of how to loop the response within your $.get callback
http://jsfiddle.net/Y3N4S/
$.each(json.children, function(i, item){
$('body').append('<p>Name: '+item.name+' , Size: '+item.size+'</p>')
})
Well, working with Objects is the intend of "Javascript Object Notation".
Actually, your json is an Array of Objects.
{
"children": [ // <-- Array
{...},// <- Object
{...} // <- Object
]
}
You can access your key-value pairs this way: children[0].name
for (var i=0;i< children.length; ++){
console.log( children[i].name);
console.log( children[i].size);
}

Categories

Resources