hello everyone i want to render the json response returned from server for that i'm using map method. But there is a mistake in my code please help me to figure it..The response i'm getting is
response.json
{
status: true
token:{
access_token: "BhTErqRtliUG#8"
client_id: "ck4fLr08YHkW2y"
expires: "2018-02-19 03:51:50"
scope: null
user_id:465
},
user:{
avatar: "https://www.indianeconomy.net/lms/wp-content/uploads/2017/11/favicon.png"
email: "tet#wehubs.afs"
id:465
name: "testere"
sub:""
}
}
I've tried this
fetch(''{
.... }).then((responseData)=>{
this.setState({
userdetail: responseData,
loaded:true,
})
}
render(){
return this.state.userdetail.map(user=>{
<Text>{token.access_token}</Text>
})
}
How to use map method over above json response?
The other comments are correct. You cannot map over an object like this. There are ways you can iterate over object properties:
for(let prop in object) {
console.log(object[prop]);
}
However, in your example the objects don't have any similarities so you would not get any benefit from iterating over them.
If instead, you wanted to display the access token, you would do the following:
return (
<Text>{this.state.userdetail.token.access_token}</Text>
);
json string shown by you is not a valid json you can validate here https://jsonlint.com/
i am not sure about react but you mention dict so in python if you have valid json
you can map it with dict like this
json.loads(json_string)
Related
I've created a basic function in my component TS file to make a post request to retrieve data from a server. This function works fine but when I try to place the array of data into a variable so I can then write it on page via HTML, I can't seem to get the desired effect. It seems as if I'm doing something wrong which is causing the data not to be written into the "json" variable.
Here is my component TS, the variable I'm trying to pass the data through to is 'json';
postData = {
command: 'get_feature',
classes: 'F,G',
}
url = "http://c****************"
json;
constructor(private http: HttpClient) {
this.http.post(this.url, this.postData).toPromise().then((data:any) => {
console.log("post request in progress")
console.log("printing data array")
console.log(data)
this.json = data.json
console.log("printing json variable")
console.log(this.json)
console.log("post request finished")
});
}
And here is the basic HTML, it should only write the type of data, because I haven't stringified the data yet but it's writing absolutely nothing as if there is nothing in the variable.
<pre>
JSON test
{{ json }}
</pre>
the correct usage would be
// post is generic, so you can pass type here, if no type - pass any
this.http.post<ResponseType>(this.url, this.postData).toPromise().then((data) => {
this.json = data
});
and you can't just render the huge json in the mteplate, but you can try json pipe, to see what is inside of that json
<pre>
JSON test
{{ json | json }}
</pre>
When I have this kind of object:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
serviceProduced: {
min:"2015-03-01"
}
}
and I pass it via $http get as params:
$http({
url: '/foo'
method: 'GET'
params: myObj
});
for some reason it comes to server like this after its JSONified by $http:
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":"{\"min\":\"2015-03-01\"}"}
How can I prevent the 'serviceProduced' not to be converted to string? So that it would be like this (correct):
{"accountNumber":"1191009461","limit":"10","offset":"0","serviceProduced":{"min":"2015-03-01"}}
I think you are miss using http get. It is not supposed to support nested objects.
It should be in the following format: ?accountNumber=1191009461&limit=10&...
However, if you want to achieve what you are looking for, you can configure your object to be like:
myObj = {
accountNumber:"12345",
limit:"10",
offset:"0",
"serviceProduced.min": "2015-03-01", // you should be able to handle this format server side.
// OR
"serviceProduced[min]": "2015-03-01"
}
try:
$http.get("#{url}", myObj)...
it should work.
I've been banging my head against deserializing data with Ember. I feel like I've set it up right but I keep getting the same error. I'm trying to use the EmbeddedRecords Mixin, but it simply hasn't worked for me. Below is my debug data.
DEBUG: Ember : 1.6.1
DEBUG: Ember Data : 1.0.0-beta.7+canary.b45e23ba
DEBUG: Handlebars : 1.3.0
DEBUG: jQuery : 1.10.2
DEBUG: Model Fragments : 0.2.2
Here is a simple setup of what I've been doing. I have my model defined like this -
App.Subject = DS.Model.extend({
title: DS.attr('string'),
sections: DS.hasMany('section')
});
App.Section = DS.Model.extend({
title: DS.attr('string'),
subject: DS.belongsTo('subject')
});
App.SubjectSerializer = DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
sections: { embedded: 'always' }
}
});
and here is the format of the JSON payload I'm sending for a 'show'
{
"subject": {
"_id":"549987b098909eef0ac2d691",
"title":"Maths",
"sections":[{
"title":"Precalc",
"_id":"549987b098909eef0ac2d693"
}, {
"title":"Calc",
"_id":"549987b098909eef0ac2d692"
}],"__v":0
}
}
I get the errors in the console
Error while processing route: subjects.show undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
highered.js:16581 undefined is not a function TypeError: undefined is not a function
at Ember.Mixin.create.extractSingle (http://localhost:3300/js/highered.js:2043:25)
at apply (http://localhost:3300/js/highered.js:20664:27)
at superWrapper [as extractSingle] (http://localhost:3300/js/highered.js:20240:15)
at Ember.Object.extend.extractFind (http://localhost:3300/js/highered.js:4007:21)
at Ember.Object.extend.extract (http://localhost:3300/js/highered.js:3892:37)
at http://localhost:3300/js/highered.js:11864:34
at invokeCallback (http://localhost:3300/js/highered.js:23228:19)
at publish (http://localhost:3300/js/highered.js:22898:9)
at publishFulfillment (http://localhost:3300/js/highered.js:23318:7)
at http://localhost:3300/js/highered.js:28736:9
Which as best I can tell is directly related to extractSingle at the this.keyForAttribute method
extractSingle: function(store, primaryType, payload, recordId, requestType) {
var root = this.keyForAttribute(primaryType.typeKey),
partial = payload[root];
updatePayloadWithEmbedded(store, this, primaryType, partial, payload);
return this._super(store, primaryType, payload, recordId, requestType);
},
although an interesting thing to note is that the error occurs at extractArray when I am using the subjects index route, which return the json above but with array brackets as well.
extractArray: function(store, type, payload) {
var root = this.keyForAttribute(type.typeKey),
partials = payload[pluralize(root)];
forEach(partials, function(partial) {
updatePayloadWithEmbedded(store, this, type, partial, payload);
}, this);
return this._super(store, type, payload);
}
Which makes me think that Ember Data is having trouble recognizing the format. This happens any time I define a serializer for a model, not just when I enable embedded records.
I'm hoping someone will be able to explain this. As a final note I've been using the Ember Data Model Fragments library as well, but I disabled that and still got this error so I don't think that is it.
The Embedded Records mixin doesn't work with the RESTSerializer before beta 9.
You can view the state of it here Ember-data embedded records current state?
You'll also want to be wary of updating ember or ember data without the other version in certain circumstances. Ember Data cannot read property 'async' of undefined
Good day! I need to render a model's attributes to JSON so I can pass them into a template.
Model:
var UserInfo = Backbone.Model.extend({
url: appConfig.baseURL + "users/",
});
Template:
<script type="text/html" class="template" id="profile-form">
<h2 class="ui-li-heading"><%= username %></h2>
<p class="ui-li-desc"><strong><%= phone %></strong></p>
</script>
View:
var ProfilePageView = Backbone.View.extend({
events: {
'click #edit': "edit"
},
initialize: function () {
this.template = $.tpl['profile-form'];
var user = new UserInfo()
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
console.log(user) //returns correct object with attrs
console.log(user.toJSON()) //returns empty object
},
render: function (eventName) {
$(this.el).html(this.template());
},
edit: function () {
window.workspace.navigate('#account/edit', { trigger: true});
}
});
When i put in console something like this, user.toJSON() returns correct data
var user = new UserInfo();
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST'
});
But when i put it to my view, its returns Object {}.
Where is a mistake or tell me how can differently pass to the template data received from the server in json format? Thanks!
You appear to have two problems. fetch is asyncronous, so you need to use a callback to use the information. But first, an explanation about toJSON. .toJSON() doesn't actually return a JSON string, it returns an object that is what you want JSON to stringify. This allows you to modify the toJSON method to customize what attributes will be taken from your model or collection and added to the JSON string representation of your model. Here is a quotation from the Backbone.js docs:
toJSON collection.toJSON([options])
Return a shallow copy of the model's attributes for JSON
stringification. This can be used for persistence, serialization, or
for augmentation before being sent to the server. The name of this
method is a bit confusing, as it doesn't actually return a JSON string
— but I'm afraid that it's the way that the JavaScript API for
JSON.stringify works.
So you should replace this line in your code
console.log(user.toJSON())
with this one
console.log(JSON.stringify(user))
The object that you saw was returned by toJSON will then be turned into JSON.
Now, even after you do that, it won't work properly, because you will execute the console.log before you get the data for your model from fetch. fetch is asynchronous, so you need to call any code you want to be executed after the fetch is done in the success callback:
user.fetch({
data: $.param({email: localStorage.getItem('user_email')}),
type: 'POST',
success: function(){
console.log(user);
console.log(JSON.stringify(user));
}
});
I am new to Backbones.js, and I was trying to get my JSON urls and parse them correctly.
This is my code:
window.Post = Backbone.Model.extend({
initialize: function(options) {
this.id = options.id;
},
url: function() {
return 'api/get_post/?post_type=movies&id=' + this.id;
},
parse : function(response) {
return response.posts;
},
});
window.Posts = Backbone.Collection.extend({
model: Post,
defaults: {
model: Post,
},
url: "api/get_recent_posts/?post_type=movies",
parse : function(response) {
return response.posts;
},
});
It seems that parsing for both overrides each other or something. when I remove the parse option from the Post class, I get a full response from the collection, but not from the model.
Are there any clear examples on how to set parsing for different son hierarchies? my JSON result have a status ok before it dives into the actual data.
I've never used bones.js but maybe these examples will help.
I think what you want to do is get rid of the parse() function in your collection. This assumes that since it is a Post collection, your data will come in as an array of Post JSON objects [{id:'1', 'sub':{data}},{id:'2', 'sub':{data}},{id:'3', 'sub':{data}}] or something like that.
If your Post model has sub-models or collections, your model parse() will then take the sub-object property name and do something with it.
// In Post Model definition
parse:function(response) {
if (response.sub) {
// create some model or collection etc.
}
}
You might have to pass an option parse:true when you do your collection fetch.
I posted something along these lines which might help you see how sub-models can be instantiated on fetch calls.
Backbone.js: Load multiple collections with one request
Cast/initialize submodels of a Backbone Model
I hope this helps.