I have three data coming back from an ajax call. I pack them into an array like this:
return json_encode([$salesOrder, $soAddressDetails, $lineItems]);
I then go to the view and look at the return. I see (as an example) this:
[
[{
"id": 8591,
"reference": "MYCLIENT",
"name": "MYCLIENT COMPANY \u00a3",
"allocated_status": "",
"created_at": "2016-12-02 09:31:00",
"order_date": "2016-12-02",
"cust_order_number": "",
"del_name": "",
"consignment": "",
"despatch_date": "0000-00-00",
"notes_2": ""
}],
[],
[{
"id": 11691,
"qty_ordered": 1,
"qty_delivered": 0,
"sales_order_id": 8591,
"due_date": "2016-12-30",
"stock_code": "ABC-ABDCDE-01",
"record_deleted": 0,
"updated_at": null,
"unit_price": 0,
"sales_order_item_id": null,
"comment": null,
"created_at": null,
"firmware_version": null,
"units_assigned": null
},
{
"id": 11692,
"qty_ordered": 1,
"qty_delivered": 0,
"sales_order_id": 8591,
"due_date": "0000-00-00",
"stock_code": "MISCELLANEOUS",
"record_deleted": 0,
"updated_at": null,
"unit_price": 232,
"sales_order_item_id": null,
"comment": null,
"created_at": null,
"firmware_version": null,
"units_assigned": null
}
]
]
In theory all I should need to access this, as array result is:
result[0] // sales order details
result[2] // line items = array of objects
so
result[0].reference == 'MYCLIENT'
and
result[2][0].stockcode == 'ABC-ABDCDE-01
but it won't let me do that. if I console.log(result[0]) the result is [, if I console.log(result[0][0].id) the result is undefined.
what am I doing wrong?
From the last line of your question, seems like your result is still a string.
Try doing JSON.parse(result)
Either you need to say that your response will be Json in your ajax like this
dataType: 'json'
Or after getting response you have to convert it into json object
response = JSON.parse(response);
I think you just miss the level. The reference it's also in a second level. So you need to access it like:
console.info(result[0][0].reference)
Related
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
})
I have an API which has response as below:
"message": "Success!",
"user": {
"id": 17,
"first_name_kanji_or_hiragana": "Hiragana",
"last_name_kanji_or_hiragana": "Name",
"first_name_katakana": null,
"last_name_katakana": null,
"email": "user#example.com",
"image_path": null,
"email_verified_at": "2019-03-06 04:44:46",
"type": "admin",
"created_at": "2019-03-06 04:44:46",
"updated_at": "2019-03-06 04:44:46",
"deleted_at": null,
"full_name": "Name Hiragana",
"full_image_path": null,
"roles": [
Each time when i am running the API new user id is generating. What i want to do is that i want to fetch the id each time i run the api & then want to use that id in next response.
I have used below code to fetch the id but it's not working
pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody);
jsonData.data.user[0].id
pm.test(responseBody, true)
var jsonData = JSON.parse(responseBody);
jsonData.data.user[0].id // youre access the user if its array its not
Just use jsonData.data.user.id or jsonData.data.user[id]
You are trying to access an array called user
jsonData.data.user[0].id
But user is an object, so you need to access:
jsonData.data.user.id
There are sometimes that you need to check the complete json directly from your request.
user is not an array. Try the below one.
jsonData.data.user.id
Your solution will work when you have the JSON like below,
"lib_folders": {
"changed": false,
"examined": 5,
"failed": false,
"files": [
{
"atime": 1549608521.3831923,
"ctime": 1548742613.5470872,
"path": "/root/abc/xyz",
"xusr": true
},
{
"atime": 1549608521.4031928,
"ctime": 1548742462.3279672,
"path": "/root/123/456",
"xusr": true
}
],
"matched": 2,
"msg": ""
}
For the above JSON if you want to get the path of the first file, then use the below code,
jsonData.data.lib_folders.files[0].path
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 am having problem with my data.
My JSon looks like that:
[
{
"link": {
"created_at": "2013-10-07T13:31:43+09:00",
"id": 8,
"items_count": 4,
"key": "0iqVSnTU-BtJ1ItVKRe2VMWvRMU",
"mode": "standard",
"name": "sdasadads",
"pusher_key": "1jtsrzl3n6i1DKA3tSZJM6LPnfQ",
"readonly_key": "R_dD5oHMsruu0YzYVKEOA8hKKXA-r",
"updated_at": "2013-10-08T14:06:07+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-07T13:32:56+09:00",
"id": 9,
"items_count": 1,
"key": "Mj-6Cc-_qaGlVTPgqKexzeijYNA",
"mode": "standard",
"name": "Untitled2",
"pusher_key": "hGE0D8TSar_H_Gv9MWdpj26gamM",
"readonly_key": "T53SNKPgyf7KvRUMzDQPaM99AAc-r",
"updated_at": "2013-10-07T13:33:14+09:00",
"user_id": 2
}
},
{
"link": {
"created_at": "2013-10-11T11:18:06+09:00",
"id": 10,
"items_count": 0,
"key": "X_ZoKxFPHtsvSU5W11gXx1653FU",
"mode": "standard",
"name": "Usdadasas",
"pusher_key": "0PZ860awofRKB9XIrXba-xY6u14",
"readonly_key": "2rzrRZAaR7UZRK3UbUId8xmFzd4-r",
"updated_at": "2013-10-11T11:18:06+09:00",
"user_id": 2
}
}
}
I am trying to print put all the names of the links like that:
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[link][0].name;
});
but it doesn't work.
How can I grub all the names and put it in html?
The objects are inside the array, not the other way around.
link is a literal property name, not a variable containing one as a string
Thus:
data[0]['link']['name']
You'll also need to make sure that the response has an application/json content type.
Grabbing all the names will require you to use a loop and change the 0 each time round it.
First of all change last "}" to "]" (your top structure is array not object )
Then try this
$.post( "http://0.0.0.0:9292/api/links", function( data ) {
document.getElementById("test").innerHTML = data[0].link.name;
});
Array.prototype.map() is a good way to fetch something from data structure. With your test data in data variable, could would look like this:
Example here.
<div class="names"></div>
var names = data.map(function (item) {
return item.link.name
});
document.querySelector(".names").innerHTML = names;