Dart| json formatting - json

I have been trying to fetch data out of JSON in flutter application.
I have tested the API request and formatting in python before making the application and all seems right
Python code:
for data in results['sections']:
for restaurant in data['items']:
restaurantName = restaurant['title']
restaurantImage = restaurant['image']['url']
for detail in restaurant:
if detail == 'venue':
restaurantAddress = restaurant['venue']['address']
restaurantDeliveryPrice = restaurant['venue']['delivery_price']
restaurantDeliveryETA = restaurant['venue']['estimate_range']
restaurantOnline = restaurant['venue']['online']
restaurantTags = restaurant['venue']['tags']
but when trying to get the data in flutter it doesn't return any feedback after
"for detail in restaurant:"
Dart code :
for (var data in jsonResponse['sections']) {
for (var restaurant in data['items']) {
var restaurantName = restaurant['title'];
var restaurantImage = restaurant['image']['url'];
print(restaurant);
}
}
Example restaurant json:
{filtering: {filters: [{id: primary, values: [hummus, kosher-for-passover, kosher]}]}, image: {blurhash: j6RIaL4iPuN3XKHdlktkX;OWgOmY, url: https://prod-wolt-venue-images-cdn.wolt.com/5fc619b23e62b6b24328928f/e122a0f8-3897-11eb-8333-de04af82ec5b_list1.jpg, variants: [xs, sm, md, frontpage]}, link: {target: 5fc619b23e62b6b24328928f, target_sort: default, target_title: , title: , type: venue-id, venue_mainimage_blurhash: j4OXin0g6J00Tl;;;mch7vgPV2WX}, overlay: Temporarily offline, sorting: {sortables: [{id: delivery-price, value: 1013}, {id: rating, value: 846}, {id: delivery-estimate, value: 946}, {id: distance, value: 1016}]}, template: venue-large, title: Hummus Hakerem | Shoken, track_id: venue-hummus-hakerem, venue: {address: שוקן 30 תל אביב , badges: [{text: KOSHER, variant: secondary}], categories: [], city: , country: ISR, currency: ILS, delivers: false, delivery_price: ₪18.00, delivery_price_highlight: false, delivery_price_int: 1800, estimate: 30, estimate_range: 25-35, franchise: , id: 5fc619b23e62b6b24328928f, location: [34.7720054, 32.0515629], name: Hummus Hakerem | Shoken, online: false, price_range: 1, product_line: restaurant, promotions: [], rating: {rating: 4, score: 9.2}, short_description: Simply great hummus, show_wolt_plus: false, slug: hummus-hakerem, tags: [kosher]}}
when trying to program the "for detail in restaurant:" loop in dart the app just loop endlessly

Related

PUT Request with Query Parameters using InMemoryDatabase Angular 8

I am trying to make a PUT request for an object that doesn't contain an exact 'id' key. I am using the Angular InMemory Database service. The Object structure is as follows:
{
students: [{
name: 'jim',
age: 10,
grade: 4,
},{
name: 'james',
age: 11,
grade: 5,
}]
}
Service Method
updateStudent(student: Student) {
const url = 'api/students'
const options = { name: student.name };
return this.httpClient.put(url, student, { params: options }).pipe(
tap(_ => console.log('student updated)),
catchError(this.handleError('updating student'))
);
}
Component Method
updateStudent() {
this.studentService.updateStudent(this.selectedStudent).subscribe();
}
Where selectedStudent is:
{
name: 'jim',
age: 12,
grade: 6
}
If I change the PUT to a GET the in memory database come back with the correct student in the array. But with the code stated above I get a 404 Error

Correct normalizer syntax for normalizing JSON

I'm trying to use normalizer to normalize some JSON. My JSON looks like
total: 8029,
items: [
{
id: 1,
name: 'Jacket1',
sku: '123',
upc: '1',
price: '99.99',
images: ['url1', 'url2'],
category: 'clothing',
thumbnail:
'https://cdn.zeplin.io/5969021e44c5978909d5278b/assets/1CE5FF07-E70F-4413-85BF-49C08AA559DE.png',
}, ...
and from the examples, I thought this might work
const itemSchema = new schema.Entity('items')
const itemsSchema = new schema.Entity('result', {
items: [itemSchema],
})
const foo = normalize(fakeDatabase, itemsSchema)
But I end up with one result that is undefined, and that undefined value has some funky stuff in it.
What am I doing wrong?
I don't believe itemsSchema is necessary. Try either:
normalize(fakeDatabase, { items: new schema.Array(itemSchema) })
or
normalize(fakeDatabase, { items: [itemSchema] })

How to replace value in JSON object in Node.js

I want to replace the value in existing JSON object in Node.js
Code :
var designationName='Softwar Engineer';
console.log(generateData[0]);
Console Output:
{
email: 'xxxxxx#gmail.com',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
}
In the above console output 'designation' value printed as '10'
Expected Result:
I want to replace "designation: Software Engineer" instead of "designation:10"
Considering generateData[0] contains the following json which you fetch from a database
{
email: 'xxxxxx#gmail.com',
designation: 10,
id: 274,
first_name: 'firstname',
mobile: '1234567890',
last_name: 'lastname'
};
To replace "designation: Software Engineer" instead of "designation:10"
var designationName = 'Software Engineer';
if(generateData[0]){
generateData[0]['designation']= designationName;
}
console.log(generateData[0]);
var designationName='Softwar Engineer';
if( generateData.length && generateData[0].designation)
{
generateData[0].designation = designationName;
}
console.log(generateData[0]);

Preprocessing Mongoose documents right after querying

Abstract
Hi, I have two models City and Country:
var Country = new Schema({
name: String,
population: String
});
var City = new Schema({
name: String,
timeZone: { type: Number, min: -12, max: 12 },
summerTime: Boolean,
country: { type: Schema.ObjectId, ref: 'Country'}
});
When I'm querying data from mongo using the following way:
function (request, response) {
var CityModel = mongoose.model('City', City);
CityModel.find().lean().populate('country').exec(function(err, docs){
response.send(JSON.stringify(docs));
});
}
But on client when I parse JSON, I get multiple instances of the same country:
var cities = $.get('/cities').then(function(citiesJson){
var cities = JSON.parse(citiesJson);
var washingtonIndex = ...;
var californiaIndex = ...;
var washington = cities[washingtonIndex];
var california = cities[californiaIndex];
washington.country.population = "300 000 000";
california.country.population = "500 000 000";
console.log([california.country.population, california.country.population]);
});
Resulting with two values ["300 000 000", "500 000 000"] in the console.
The problem
To prevent this kind of behaviour and preserve object references I'm doing JSON.decycle before object serialization:
...
response.send(JSON.stringify(JSON.decycle(docs)));
...
It works better than it should be. As a result I get the following JSON on the client:
// City:
{
name: "Bost",
deleted: "0",
country: {
$ref: "$[0]["city"]["country"]"
},
lastModified: "2013-08-06T23:44:11.000Z",
_id: {
_bsontype: "ObjectID",
id: "Rm1'"
},
approved: "1"
}
Notice the _id field which is getting serialized by reference so I don't get the actual ObjectId's string representation on the client, instead I'm getting some internal mongo representation of the id which is not usable on the client.
The question
1) Is there a way to setup per model or per schema preprocessing for all queried documents so that I convert ObjectId's into string
2) Probably there is some other more efficient way of dealing with this problem?
Thanks

Serializing/Deserializing nested Backbone Relational models to JSON

Given the following RelationalModel model:
var Server = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'databases',
relatedModel: 'Database',
collectionType: 'DatabaseCollection',
includeInJSON: 'id'
}],
defaults: {
databases: []
},
});
var Database = Backbone.RelationalModel.extend({});
var DatabaseCollection = Backbone.Collection.extend({
model: Database
});
And these objects:
new Database({
id: 1,
name: 'DB1'
});
new Database({
id: 2,
name: 'DB2'
});
var s1 = new Server({
id: 3,
name: 'S1',
databases: [1,2]
});
What would be the easiest/recommended way to serialize/deserialize this model to something aproaching this JSON structure?:
{
databases: [
{ id: 1, name: 'DB1' }
{ id: 2, name: 'DB2' }
],
servers: [
{ id: 3, name: 'S1', databases: [1, 2] }
]
}
Such that the data can be sent to / read from the server in a single request.
Thanks!
Tim
I was able to produce the JSON you described using your example with some minor changes in this fiddle I just created Example.
I made these changes due to some warnings that were being shown in the debugger and to get the result you described. Hope this helps.
Moved the declaration of Database Model and DatabaseCollection to top before Server since Servers relatedModel and CollectionType point to those Models.
For relatedModel and collectionType instead of using Strings used the reference to Database and DatabaseCollection
Created a collection for Servers called ServerCollection
Added a few more examples
Here is the code you end up with, I just created a plain old Backbone model to combine the two collection into one. Calling toJSON gives you the single JSON object to transmit to the server.
var Database = Backbone.RelationalModel.extend({});
var DatabaseCollection = Backbone.Collection.extend({
model: Database
});
var Server = Backbone.RelationalModel.extend({
relations: [{
type: Backbone.HasMany,
key: 'databases',
relatedModel: Database,
collectionType: DatabaseCollection,
includeInJSON: 'id'
}],
defaults: {
databases: []
}
});
var ServerCollection = Backbone.Collection.extend({
model: Server
});
var allDatabases = new DatabaseCollection();
allDatabases.add([
new Database({ id: 1, name: 'DB1' }),
new Database({ id: 2, name: 'DB2' }),
new Database({ id: 3, name: 'DB3' }),
new Database({ id: 4, name: 'DB4' })
]);
var allServers = new ServerCollection();
allServers.add([
new Server({
id: 30,
name: 'S1',
databases: [
allDatabases.get(1),
allDatabases.get(2)
]
}),
new Server({
id: 40,
name: 'S2',
databases: [
allDatabases.get(3),
allDatabases.get(4)
]
})
]);
// combine into an object to transfer to server as one
var serverObject = new Backbone.Model({
'servers': allServers,
'databases': allDatabases
});
console.log(serverObject.toJSON());