I get an array from the API as follows:
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113660 } ]
However I expect
[ { "URL": "", "avatar": "", "characterID": 853, "creationDate": "2022-01-22T17:12:42", "description": "description", "foreignSuggestionID": 0, "id": 5, "seriesID": 0, "type": "IMAGE", "userID": 168314031248113664} ]
The userID gets transformed in the request by Javascript, since when I use transformResponse: data => data I get the correct ID.
This gets me to the conclusion that it cannot contain the large number in Javascript. My question here would be, is there a way to make sure that a specific value within the json array is seen as a bigint or can I convert the column into a string on receiving the response?
I use axios and my code is as follows:
this.$axios.get(url, {
withCredentials: 'true'
})
.then(response => {
this.data = response.data
})
Related
I am attempting to create a JSON Object from an array to pass into a Microsoft product. The format in which the JSON object is accepted is shown beneath (content-type: "application/json"):
{
"value": [
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1668987+00:00",
"externalId": "Test--8586509942423126760MS164-0",
"fileHashType": "sha256",
"fileHashValue": "b555c45c5b1b01304217e72118d6ca1b14b7013644a078273cea27bbdc1cf9d6",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
},
{
"activityGroupNames": [],
"confidence": 0,
"description": "This is a canary indicator for demo purpose. Take no action on any observables set in this indicator.",
"expirationDateTime": "2019-03-01T21:44:03.1748779+00:00",
"externalId": "Test--8586509942423126760MS164-1",
"fileHashType": "sha256",
"fileHashValue": "1796b433950990b28d6a22456c9d2b58ced1bdfcdf5f16f7e39d6b9bdca4213b",
"killChain": [],
"malwareFamilyNames": [],
"severity": 0,
"tags": [],
"targetProduct": "Azure Sentinel",
"threatType": "WatchList",
"tlpLevel": "green",
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
The workflowContext.actions.Compose.outputs line pulls an array consisting of objects shown in the following snippet:
[{"id": "1", "activityGroupNames": "test2"}, {"id": "2", "activityGroupNames": "test3"}, {"id": "3", "activityGroupNames": "test4"}]
This is my output:
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
it is pretty much identical to the format described my Microsoft shown in the first snippet. (https://learn.microsoft.com/en-us/graph/api/tiindicator-submittiindicators?view=graph-rest-beta&tabs=http) at the bottom.
I am unsure as to how I can change the key name from "body" to "value" and think maybe this will resolve my issue. Either way, I'd appreciate any other help on the matter, if any more context is required, please ask.
EDIT: The image beneath shows that the returned return value; is in fact being used as the input for a POST request to the Microsoft graph API
I'm accessing a JSON that comes back looking like this:
[
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"selectionType": "Music",
"sfzFile": "",
"destination": "/data/uploads",
"encoding": "7bit",
"fieldname": "file",
"filename": "782f49a7cd72b865b4e2d286816792e7",
...
"found": true,
"flError": false,
"error_strings": [],
"_id": "5ada2217c114ca048e1db9af",
"created_by": "5ab57289d8d00507b29a3fdd",
"slug": "1105fmid",
"__v": 0,
"createdAt": "2018-04-20T17:23:35.216Z",
"updatedAt": "2018-04-20T17:23:35.788Z",
"selectionTitles": null,
"id": "5ada2217c114ca048e1db9af"
},
"slug": "1105fmid",
"createdAt": "2018-04-20T17:23:35.285Z",
"updatedAt": "2018-04-20T17:23:35.285Z",
"__v": 0,
"id": "5ada2217c114ca048e1db9b0"
}, ...
The react-select node module that I am using takes the key "label" to generate a populated dropdown.
The JSON is coming from the web so I can't control how the JSON is setup. How do I parse the JSON to find all the instances of "name" and replace that key with "label" ?
For example "name" : 1105F.MID" should be changed to "label" : "1105.MID"
Would it be inefficient to convert the entire thing to a string and use the javascript method find/replace?
Assuming your JSON array is stored in the variable data:
data.forEach(item => item.label = item.name)
This would be sufficient to duplicate the name property as the label property for each item in the array.
I have created a function replace() to deal with every object and nested objects, which will add property 'label' if 'name' property is found. Pls see if it's useful to you.
var arr = [
{
"itemType": "SelectionTitle",
"name": "1105F.MID",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "1105F.MID"
}
},
{
"itemType": "SelectionTitle",
"name": "test",
"active": true,
"isFactoryDefault": false,
"factoryCode": "",
"seasons": [],
"denominations": [],
"groups": [],
"length": 0,
"_id": "5ada2217c114ca048e1db9b0",
"created_by": "5ab57289d8d00507b29a3fdd",
"selectionFile": {
"itemType": "SelectionFile",
"name": "testing"
}
}
]
// this method will take care of adding new property
function replace(obj, from, to) {
Object.entries(obj).forEach(([key, value]) => (
key == from && (obj[to] = obj[from])
, typeof value === "object" && replace(value, from, to)
))
}
arr.forEach(d => replace(d, 'name', 'label'))
// you can check this log for property 'label' whereever 'name' exists
console.log(arr)
Relying on the structure of server response is bad; especially when you say you have not control over it. A better way would be to always parse the server response, construct whatever necessary for the react-select component to work and pass that only.
Currently, this works and doesn't give my error while running but my text editor is giving me an error that says property 'categories' does not exist on type 'CategoryInterface[]' (on the line where response.categories is assigned to variable) so I'm not sure if I'm doing things right.
public categories: CategoryInterface[];
.subscribe((response: CategoryInterface[]) => {
this.categories = response.categories;
console.log(this.categories);
});
My backend returns this:
{
"categories": [
{
"categoryId": 1,
"name": "Important",
"description": "This category is important.",
"order": 1,
"createdBy": null,
"createdAt": "2017-11-25 12:09:04",
"updatedBy": null,
"updatedAt": "2018-01-17 23:53:25",
"categoryBoards": [
{
"categoryBoardId": 1,
"categoryId": 1,
"name": "Announcements",
"description": null,
"order": 2,
"createdBy": null,
"createdAt": "2017-11-25 12:09:49",
"updatedBy": null,
"updatedAt": "2018-01-18 00:09:02"
},
{
"categoryBoardId": 23,
"categoryId": 1,
"name": "Rules",
"description": null,
"order": 1,
"createdBy": null,
"createdAt": "2018-01-18 00:08:57",
"updatedBy": null,
"updatedAt": "2018-01-19 00:05:51"
}
]
}
]
}
You are trying to cast your api response to an array of CategoryInterface which is not the case, you better use your subscribe method like this:
.subscribe((response: any) => {
this.categories = <CategoryInterface[]> response.categories;
console.log(this.categories);
});
It's the your api response categories which needs to be casted to CategoryInterface[]
Bonus: The angular style-guide notice that you need to declare classes instead of interfaces and you don't have to suffix the class name with Interface, so just name your CategoryInterface to Category.
You get the error because you declare response as a CategoryInterface[], but response.categories is actually the CategoryInterface[]. response is just a wrapper around the array. All the types are stripped out when the typescript is converted to javascript, which is why it works fine at runtime.
I'm developing a react application and in my state I have the data saved that I try to read. When I JSON.stringify the device data "console.log"'it out, look like this:
{
"ActTime": 1509988664,
"ServerTime": "2017-11-06 18:17:44",
"Sunrise": "07:25",
"Sunset": "15:53",
"result": [
{
"AddjMulti": 1,
"AddjMulti2": 1,
"AddjValue": 0,
"AddjValue2": 0,
"BatteryLevel": 255,
"CustomImage": 0,
"Data": "On",
"Description": "",
"Favorite": 1,
"HardwareID": 2,
"HardwareName": "Controller",
"HardwareType": "OpenZWave USB",
"HardwareTypeVal": 21,
"HaveDimmer": true,
"HaveGroupCmd": true,
"HaveTimeout": false,
"ID": "00000501",
"Image": "Light",
"IsSubDevice": false,
"LastUpdate": "2017-11-06 15:42:00",
"Level": 0,
"LevelInt": 0,
"MaxDimLevel": 100,
"Name": "Vardagsrum",
"Notifications": "false",
"PlanID": "0",
"PlanIDs": [
0
],
"Protected": false,
"ShowNotifications": true,
"SignalLevel": "-",
"Status": "On",
"StrParam1": "",
"StrParam2": "",
"SubType": "Switch",
"SwitchType": "On/Off",
"SwitchTypeVal": 0,
"Timers": "false",
"Type": "Light/Switch",
"TypeImg": "lightbulb",
"Unit": 1,
"Used": 1,
"UsedByCamera": false,
"XOffset": "0",
"YOffset": "0",
"idx": "3"
}
],
"status": "OK",
"title": "Devices"
}
If I want to read the status data I just do: device['status'] I get "OK", but what if I want to access the result data in the device?
I thought that device['result'][0]['Status'] would give my 'Ok, but I just get Uncaught TypeError: Cannot read property '0' of undefined ???
How do I read the result data in the device??
To do this device['result'][0]['Status'] you want to ensure your device data is not a string but a proper JSON object. You could JSON.parse() to convert it if it's not already an object.
Also ensure the data is available before trying that.
Try to use map method over result array.
Something like this:
result.map((item,index)=>{
console.log(item[index].AddjMulti);
})
I've tried 100 different things, and spend days looking through Google and Stackoverflow, but I can't find a solution to this problem. Everything I call after the body of this API response returns undefined!
The response from Facebook SDK looks like this:
[
{
"body": "[
"data": [
{
"name": "Larry Syid Wright",
"administrator": false,
"id": "xxx"
}, {
"name": "Melissa Long Jackson",
"administrator": false,
"id": "xxx"
}, {
"name": "Charlotte Masson",
"administrator": false,
"id": "xxx"
}
],
"paging": {
"next": "url"
}
]"
},{
"body": "{
"data": [
{
"id": "xxx_xxx",
"message": "In honor of Halloween, how many of you have your own ghost stories? Who believes in ghosts and who doesn't?",
"type": "status",
"created_time": "2014-10-31T20:02:01+0000",
"updated_time": "2014-11-01T02:52:51+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Joe HerBatman Owenby Jr."
}
],
}
"paging": {
"cursors":
{
"after": "xxx",
"before": "xxx"
}
}
}
},{
"id": "xxx_xxx",
"from": {
"id": "xxx",
"name": "Jessica Starling"
},
"message": "Watching the "Campaign" and I can't help but notice what a fantastic job they did (Will ferrell and all) with that North Carolina accent! Ya'll know we sound different than other southern states ;)",
"type": "status",
"created_time": "2014-11-01T02:36:21+0000",
"updated_time": "2014-11-01T02:36:21+0000",
"likes": {
"data": [
{
"id": "xxx",
"name": "Scott Williams"n
}
]
}
}
],
"paging": {
"previous": "xxx",
"next": "xxx"
}
}"
}
]
This response is from a batch call. If I call them separately, I can easily iterate through the responses, and get everything from them. When I call them in the batch though, I can't get past "body", and I need to use a batch call.
console.log(response[0].body); will return the object inside the body of the first part of the response, but console.log(response[0].body.data); returns undefined. I just don't get it. This should be simple but it's like there's a lock on the door and I don't have the right key.
I normally have no issue iterating through objects, so I don't need a generalized answer. I need help seeing whatever it is here that I don't see. Why does the console show undefined when I call anything after the body, and what do I need to be doing to get any of these values?
That JSON contains nested JSON. body seems to be a string. Use
var body = JSON.parse(response[0].body);
The values from the body are just strings.which are embedded as json.So firstly you would need to parse them using JSON.parse.
The code would be like
var body = JSON.parse(response[0].body);