I have a json file like this:
"_id": {
"$oid": "d8"
},
"timestamp": {
"$date": "2010-09-03T11:53:22Z"
},
"name": {
"$ref": "user",
"$id": "73e"
},
and in backbone collection I have this, and i want to fetch data from url.
defaults : {
id : null,
name : null,
timestamp : null
},
parse : function(response){
response.id = response._id.$oid;
response.timestamp = response.timestamp.$date;
response.name = response.name.$ref;
return response;
},
it recognize everything except ref and it ways this error.
Uncaught TypeError: Cannot read property '$ref' of undefined. Why is it like that?
You got JSON that you do not expect to get. You always have to check if object exists before accessing it properties:
parse : function (response) {
response._id && (response.id = response._id.$oid);
response.timestamp && (response.timestamp = response.timestamp.$date);
response.name && (response.name = response.name.$ref);
return response;
}
Please add to your question console output: console.log(response);
Related
Good healty everyone, I want to ask something about managing data from JSON. I've JSON format like below :
{
"msg": "Success"
"data": [
{
"id": "1",
"notelp": "0000000000",
"user": "no1"
},
{
"id": "2",
"notelp": "1111111111",
"user": "no2"
},
],}
and I want to get value from variable "notelp", I expect output like this {"0000000000", "1111111111",} how to get it ?
I tried this before, but still can't get what I want,
if (response.statusCode == 200) {
final result = json.decode(response.body);
debugPrint('dataTelp: ${result['data']['notelp']}');
}
thank you guys to help me to solve it and stay save.
You can use the forEach or another looping method to get data from a list.
List outPut = [];
List data = response['data'];
data.forEach((element) {
outPut.add(element['notelp']);
});
print(outPut);
I have this function:
fun getFeed(token: String): Result<Array<Post?>, Exception> {
if (token != "") {
val (request, response, result) = "https://alles.cx/api/feed"
.httpGet()
.header("Authorization", token.toString())
.response()
when (result) {
is Result.Success -> {
println("Result success")
try {
val responseJSON = JSONObject(String(response.data))
if (!responseJSON.has("err")) {
println("Has no error")
var feedArray = arrayOfNulls<Post>(0)
println("HERE?")
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
println("not here")
println("Made to the for")
for (i in 0 until feed.length()) {
println("For $i")
val jsonObject = feed.getJSONObject(i)
var imageURL: URL? = null
if (jsonObject.has("image")) {
imageURL = URL(jsonObject["image"].toString())
}
feedArray[i] = Post(
jsonObject.getString("id"),
User(jsonObject.getJSONObject("author").getString("id"), jsonObject.getJSONObject("author").getString("username"), jsonObject.getJSONObject("author").getString("name")),
jsonObject.getString("createdAt"),
jsonObject.getInt("replyCount"),
jsonObject.getInt("score"),
jsonObject.getString("content"),
null,
imageURL,
jsonObject.getInt("vote")
)
println("Added post $i")
}
println(feedArray)
return Result.Success(feedArray)
}
else {
println("yes error")
return Result.Failure(Exception(responseJSON["err"].toString()))
}
}
catch(e: Exception) {
return Result.Failure(e)
}
}
is Result.Failure -> {
return Result.Failure(Exception(result.component2()?.localizedMessage))
}
}
}
else {
return Result.Failure(Exception("badAuth"))
}
}
An error is occurring on this line. I know this because of the print statements that are in the code:
var feed = JSONArray(responseJSON["feed"]) // <-----ERROR HERE
This is what the error that is occurring is.
[Failure: org.json.JSONException: Not a primitive array: class org.json.JSONArray]
This is what the feed object from the get request will look like, just so you have an idea of what it is:
{
"feed": [
{
"type": "post",
"slug": "equ2ZfaX2UThtkS8DzkXdc",
"author": {
"id": "00000000-0000-0000-0000-000000000000",
"name": "Archie",
"username": "archie",
"plus": true
},
"content": "I know it's quite inactive here atm. But I'm doing tons of stuff behind the scenes - basically rewriting the entire platform from scratch. Micro will be done by the end of the summer.",
"image": null,
"createdAt": "2020-07-30T20:39:23.000Z",
"score": 5,
"vote": 0,
"replyCount": 0,
"hasParent": false
}
]
}
What could possibly be going wrong here. I am using Fuel for the request, but I don't think that is the problem
Pretty sure the correct way to get the array would be to do var feed = responseJSON.getJSONArray("feed"). You're implementation calls the JSONArray(Object o) constructor which is meant to be called only for primitive arrays (int[], double[], etc.) as they cannot be effectively typed using generics). Thus the constructor complains as you pass in an object which is not a primitive array.
I have a http.post request which sends an object as a parameter, the expected format is like this:
var searchQuery;
var subj;
var body;
var startDate;
var endDate;
{
"search": {
"scope": [2,3,32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
The problem is some values are optional meaning that if I don't provide searchQuery as a string then the whole key value should be ingnored, e.g "value": searchqery should be not included in the json object if I did not provide value to that variable. Same goes for startDate and endDate if I don't provide values then date shouldbe ignored from the json.
So how to dynamically include or exlude key pair value in the object that coming from UI and how to build that object before sending to a post request?
Whould it be something like this?
var search = {};
search.text = { value: "", fields: [] };
{value: "", fields: Array(0)}
seach.text.value = "wes";
search.text.value = "wes";
search.text.fields.push("subject");
search.text.fields.push("body");
You can create a function that's a bit more flexible.
var searchQuery = "";
var subj = null;
var body = "";
var startDate = "";
var endDate = null;
let obj = {
"search": {
"scope": [2, 3, 32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
}
}
function removeNull(obj) {
return Object.keys(obj).reduce((res, key) => {
if (Array.isArray(obj[key])) {
// If it's an array, filter out the null items
res[key] = obj[key].filter((item) => item != null && item !== "");
} else if (typeof obj[key] === "object" && obj[key] != null) {
// If it's an object, call the function recursively
res[key] = removeNull(obj[key]);
} else if (obj[key] != null && obj[key] !== "") {
// Otherwise, only add it to the results if it's not null
res[key] = obj[key];
}
return res;
}, {});
}
console.log(removeNull(obj));
I have 2 models in my project, 1 is stores and the other is products, the stores has a reference to products like this:
produtos: [
{ type: mongoose.Schema.ObjectId, ref: 'Produto' }
]
and basicly at the moment i have a object like this:
{
"_id": "589715a3a2030f7bc143ed89",
"nome": "levis2",
"email": "filipecostaa10#gmail.com1",
"password": "1234",
"__v": 8,
"produtos": [
"58971695a2030f7bc143ed8a",
"589716d7a2030f7bc143ed8b",
"58971742a2030f7bc143ed8c",
"58971770a2030f7bc143ed8d",
"589717a1a2030f7bc143ed8e",
"58971848a2030f7bc143ed8f",
"589718f5a2030f7bc143ed90",
"58971937a2030f7bc143ed91"
],
"descricao": "No description for this store"
}
the array produtos has a lot of ids. Those ids are reference to the products; What i need to know now is how i can do a get request to get all the products with those ids, how do i send the request?
here is my router
router.get('/',function(req,res){
Loja.find(function(err,lojas){
if(!lojas){
return res.status(404).json({Error:"Loja nao encontrada"});
}
res.send(lojas);
}).populate("Produto");
})
Seems you are trying to get all stores with populated products field so:
router
.route('/')
.get(function(req, res) {
Loja
.find()
.populate('produtos')
.exec(function(err, lojas) {
if ( err ) {
return handleError(err);
}
res.json(lojas);
});
});
I'm trying to understanding backbone code. I read this
http://addyosmani.com/blog/building-spas-jquerys-best-friends/
then I plan to change this
if (this._index === null){
$.ajax({
url: 'data/blog.json',
dataType: 'json',
data: {},
success: function(data) {
ws._data = data;
console.log(ws._data);
ws._blogs = new BlogCollection(data.rows);
console.log(ws._blogs);
ws._index = new IndexView({model: ws._blogs});
Backbone.history.loadUrl();
}
});
return this;
}
return this;
use collection fetch
if (this._index === null){
ws._data = new BlogCollection;
ws._data.fetch({success: function(data){console.log(data.models[0].attributes);}});
//ws._blogs = new BlogCollection(ws._data.rows);
//ws._index = new IndexView({model: ws._blogs});
Backbone.history.loadUrl();
}
with this collection
var BlogCollection = Backbone.Collection.extend({
model: Blog,
url : 'data/blog.json',
parse: function(response){
return response;
}
when I read the response from collection, it's give same value as using jquery ajax.
but when I use fetch in controller, why I have to access data.models[0].attributes); to get the same data return.
this is my json
{ "page":"1", "total": "5", "records": "25", "rows":
[
{
"title": "Classic Pop",
"author": "Michael Jackson Collection",
"image": "images/1.jpg",
"tags": ["xyz", "abc", "def"],
"slug" : "classic-pop",
"url": "http://www.localhost/news",
"intro": "hello test",
"content": "hello test, alfjldsajfldjsflja dljfldasjfa jfljdasfl jfldsjf jljdafl jl"
},
{
"title": "Modern Pop/R&B",
"author": "Bruno Mars and Others",
"image": "images/54.jpg",
"tags": ["test", "test2", "test3"],
"slug" : "modern-pop-rb",
"url": "http://www.localhost/news",
"intro": "hello test 2",
"content": "hello test, alfjldsajfldjsflja dljfldasjfa jfljdasfl jfldsjf jljdafl jl"
}
] }
how to make fetch works right??
When extending your Backbone Collection, you should define a parse function that returns an array of rows that represent the models contained in your collection.
In your case, it must be an array of data, with each object in the array representing your Blog model, so you need to return the rows property:
var BlogCollection = Backbone.Collection.extend({
model: Blog,
url : 'data/blog.json',
parse: function(response){
return response.rows;
}
});
Then if your model has a parse function, it will get the data for each object contained in the array, in case you need to do anything with the data before the model's attributes are set:
var Blog = Backbone.Model.extend({
//data will contain one of the items returned from the collection's 'parse' function.
parse: function(data){
return data;
}
});
This will ensure that the Backbone collection will properly create and populate the models represented in the collection with the data.
You will probably want to expose the other metadata (page, total, records) on the collection too, perhaps with a property that is also a Backbone.Model of page/total/records.