iam currently developing a contact management system web app using ember js for the front end .Iam using ember store for fetching the data from the api , while fetching json data using store.findAll() , iam getting the json array with the length of data as expected but when i try to access the data at a specific position in the json array it gives undefined value , it is not giving the model value.I have checked everything like json format , naming conventions with respect to my serializer but cant able to find what is going wrong , can anyone help me with solving this ?
Application adapter :
import RESTAdapter from '#ember-data/adapter/rest';
export default class ApplicationAdapter extends RESTAdapter {
buildURL(...args) {
return "http://localhost:8082/ContactManagementSystem1/api/contact/5";
}
headers = {
'Accept': '*/*',
};
}
Json response from api :
[
{
"firstName": "Example",
"lastName": "K",
"deletedAt": "",
"mobileNumberHome": "7827382738",
"companyName": "Example",
"dateOfBirth": "2000-04-12",
"id": 21,
"userId": 4,
"mobileNumberWork": "2738273788",
"email": "rath#gmail.com"
},
{
"firstName": "nameexample2",
"lastName": "p",
"deletedAt": "",
"mobileNumberHome": "8989898996",
"companyName": "Business ",
"imageURL": "actress1.jfif",
"dateOfBirth": "2021-10-05",
"id": 51,
"userId": 4,
"mobileNumberWork": "8667889896",
"email": "nameexample2h#gmail.com"
}
]
Serializer :
import DS from 'ember-data';
export default DS.RESTSerializer.extend({
normalizeResponse(store, primaryModelClass,payload,id,requestType){
arguments[2] = {
"contacts" : payload
}
return this._super(...arguments);
}
});
Since my json response is different from the RestSerializer format i have written some code in the serializer for normalising the response.
Route where i fetch data using store.findAll()
import Route from '#ember/routing/route';
import {inject as Service } from '#ember/service';
export default class UserContactRoute extends Route {
#Service store;
async model() {
return this.store.findAll('contact');
}
}
These are codes which i have used , i have also checked in the inspect's console no error is been thrown , the problem is model array object were undefined.
One should use the objectAt(index) for accessing array elements because those arrays are not regular JS ones. See here:
It's important to note that RecordArray is not a JavaScript array,
it's an object that implements MutableArray. This is important
because, for example, if you want to retrieve records by index, the []
notation will not work--you'll have to use objectAt(index) instead.
Related
so I try to fetch data from my MongoDB collection using mongoose and typescript.
I can successfuly get fetched data but the problem I have is, that I can only access _id, season and avatar with syntax like {{response.season}} or {{response.avatar}}. Nested data inside avatar JSON object can be accessed only like it's dictionary {{response.avatar["transfer"]}} and I'm not sure why is that. I would like to access it like {{response.avatar.transfer}}, is it possible to do that ?
Fetching data from MongoDB using mongoose
export default async function run() {
// 4. Connect to MongoDB
await mongoose.connect(config.publicRuntimeConfig.MONGO_URI);
const results = await User.findOne({
'season': '123'
})
await mongoose.disconnect();
return results
}
Data I receive
{
"_id": "630fbca3d06e5e2f310ea540",
"season": 123,
"avatar": {
"from_team_id": 1,
"to_team_id": 2,
"transfer": "asdasd",
"type": "dasdasd",
"date": "asdasd",
"amount": "asdasd",
"player": {
"player_id": 12,
"country_id": 412,
"display_name": "asdasd",
"nationality": "asdasd",
"_id": "630fbca3d06e5e2f310ea542"
},
"_id": "630fbca3d06e5e2f310ea541"
},
"__v": 0
}
I want to access data like this if it's possible
<template v-for="transfer in transferData">
{{transfer.avatar.amount}}
</template>
What I can do now is
<template v-for="transfer in transferData">
{{transfer.avatar["amount"]}}
</template>
Is it possible to do that?
You can access all of the response objects properties by defining a type or interface and setting the response object as that type. I'd recommend defining a type for your avatar and player object and then one for the entire response that contains the avatar type you defined.
type response = {
"_id”:string;
avatar:Avatar
// The rest of your properties
}
type avatar = {
“from_team_id”:string;
player:Player;
// Rest of properties
}
I have a simple python (version 3.10.2) script that uses the requests library to make a REST call to an API. The call returns a list of objects. I find that the json.loads() function will not parse the JSON returned in the response. It gives me the following error:
TypeError: the JSON object must be str, bytes or bytearray, not list
Oddly, the json.dumps() function can successfully format the same data.
Here is the code:
import requests
import json
def get_groups(url):
# TODO SSL/TLS turned OFF (verify=False)
response = requests.get(url + "/groups", verify=False)
print("status code:", response.status_code)
print("JSON:\n")
print(json.dumps(response.json(), indent=2))
json.loads(response.json())
Here is an example what json.dumps() is outputting:
[
{
"id": 6,
"web_url": "https://<URL redacted>/groups/test",
"name": "test",
"path": "test",
"description": "",
"visibility": "public",
"share_with_group_lock": false,
"require_two_factor_authentication": false,
"two_factor_grace_period": 48,
"project_creation_level": "developer",
"auto_devops_enabled": null,
"subgroup_creation_level": "maintainer",
"emails_disabled": null,
"mentions_disabled": null,
"lfs_enabled": true,
"default_branch_protection": 2,
"avatar_url": null,
"request_access_enabled": true,
"full_name": "test",
"full_path": "test",
"created_at": "2021-08-03T15:41:34.523Z",
"parent_id": null,
"ldap_cn": null,
"ldap_access": null
}
]
I have seen lots of postings about this and every one mentions using json.loads() to parse the JSON data. Not sure why it works for them, but it doesn't work for me.
Any ideas as to what is wrong?
As was pointed out by #tkausl, in this case the HTTP/REST response object returns the JSON data already parsed. For some reason I missed that. I don't need to to use the json library.
I have an app where the user will search for a term and they will see the results rendered. The results, in this case, are from a nested JSON object. I have a component called CompanyInfoList that passes props to Results component that renders the JSX. The props are employee, date, tax, and balance. I tried to map within a map in the component, but it did not work. My goal is to get access to the details data, how do I do this. The files to look at are CompanyInfoList and Results. The data is loaded in via axios in CompListContext
In the CompSearch comp when you enter "ABC" nothing will happen, because I am not accessing the details data from the JSON obj. This is what I need help in doing.
Here is the mongo DB JSON object (pasted from PostMan):
"data": {
"details": {
"employee": "person1",
"date": "test date",
"tax": "test tax",
"balance": "22"
},
"company": "TEST-ABC",
"_id": "60dba9fe7641a44d40364c1f",
"__v": 0
}
Here is my code
Given the company array object shape:
{
details: {
employee: "person1",
date: "test date",
tax: "test tax",
balance: "22"
},
company: "TEST-ABC",
_id: "60dba9fe7641a44d40364c1f",
__v: 0
}
You are filtering by the element's company property, and when mapping the filtered results in CompanyInfoList you need to access the details property, i.e. result.details.employee.
const CompanyInfoList = ({ filtered }) => {
const fltr = filtered.map((result) => (
<Results
key={result.details.id}
employee={result.details.employee}
date={result.details.date}
tax={result.details.tax}
balance={result.details.balance}
/>
));
return <>{fltr}</>;
};
I have an Angular frontend which communicates with a Spring REST API. The Spring endpoint expects a JSON array, but with Angular HttpClient POST method I don't know how to send only a JSON array. Now I get HTTP error code 400 (Bad request).
What I need to send to the endpoint (this is tested and works in an API tester):
[
{
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
{
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
]
The way I'm sending the changes now:
modifyElements(id: number, elements: Element[]): Observable<Element[]> {
return this.http.post<Element[]>(this.baseUrl + '/modify/' + id, elements);
}
The structure of the data that is sent by HttpClient's put method is below:
{
"0": {
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
"1": {
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
}
What I also tried and is closer to what I need:
this.http.post<Element[]>(this.baseUrl + '/modify/' + id, {elements: elements});
What this sends:
"elements": [
{
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
{
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
]
This is still not accepted by the API, results in the same error.
Please help me how can I send the data in the right structure, only a JSON array.
I already know how can I workaround this issue in Spring: in the controller method expecting for a request body of a new class that has just one member which is a collection, but that's not a nice solution.
I would like to know how it can be done without a workaround, on the Angular side.
Edit:
Thank you for the answers so far, but they return the same array I had, with the same structure.
The data structures I inserted in the question are the request bodies sent by Angular's HttpClient, copied from Chrome DevTools.
I think the problem is not with my original array, but with how HttpClient creates the JSON that it sends.
It seems to me that it can't interpret an array as a simple JSON array, and can only send a JSON array as a key-value pair, the value being the JSON array.
What I need instead is to get rid of the key and send only the plain value.
The question is, can HttpClient do that?
I faced the same problem, and I resolved with:
return this.http.request<ReturnType>(
'POST',
URL,
{
headers: new HttpHeaders({
'Content-Type': 'application/json'
}),
body: JSON.stringify(array)
});
Use this snippet
modifyElements(id: number, elements: Element[]): Observable<Element[]> {
const elementsArray = Object.assign([], elements);
return this.http.post<Element[]>(this.baseUrl + '/modify/' + id, elementsArray );
}
This will convert to the required format
var a ={
"0": {
"date": "2020-05-26T02:00:00.000Z",
"blocked": false,
"reservation": null
},
"1": {
"date": "2020-05-27T00:00:00.000Z",
"blocked": true,
"reservation": null
}
}
var c = Object.assign([], a)
console.log(c)
as I see you have object type [key:value] ,key is index value is an element entity. you have to extract values from this object and then send it to the server
Object.values(elements) //send this
The json data is in the below pattern. And the Json data is coming from backend and getting through api and storing in a state variable.
{
"message": "user created successfully",
"status": "success",
"student": {
"class": "10",
"email": "user#gmail.com",
"name": "User",
"password": "user",
"phone_number": "some phone number",
"school": "1",
"section": "a"
}
}
I have stored the data which is returned through api in a state variable.
constructor(){
super();
this.state = {
jsonData: ''
}
}
And tried accessing using below fashion.
this.state.jsonData.status
but not able to access. How can I access the status value in react?
Please check type of jsonData in state when you call it using typeof or instanceof.
It maybe by you store fetched data in string type without check and manipulating.
If it is string type, convert it using JSON.parse