How to convert json objects to json array in flutter - arrays

This is my json response data. I would like to display this data in listview using map but i dont know how to convert the objects of objects to array of data.
{
"success": true,
"data": {
"addresses": {
"abc": {
"address_id": "121",
"firstname": "Demo",
"lastname": "User",
"company": "Demo Company name",
"telephone": "1-541-754-3011",
"address_1": "Demo",
"address_2": "test address",
"postcode": "3333",
"city": "Berlin",
"zone_id": "1256",
"zone": "Berlin",
"zone_code": "BER",
"country_id": "81",
"country": "Germany",
"longitude": "",
"lattitude": "",
"iso_code_2": "DE",
"iso_code_3": "DEU",
"address_format": "{company}\r\n{firstname} {lastname}\r\n{address_1}\r\n{address_2}\r\n{postcode} {city}\r\n{country}",
"custom_field": null
}
}
}
}

I assume you want to display dynamic keys (eg: abc) inside addresses object. For this, you need to iterate through addresses object for keys and values.
//json you provide
addresses = json["data"]["addresses"];
addresses.forEach((final String key, final value) {
//here key will be abc & value will be json object
//you can add key or value to a different list and use for list rendering later
});

You can use JSON to dart tool, which is available online for free.
Paste your JSON to left panel and select dart language from upper right corner,
You will get your dart class code, in which you can use methods like .toMap() and .toJson(),
This can be very helpful for huge JSON data.

Related

Firebase: update value in array object

I'm using Firebase DataBase in my application.
Below is my Collection data
Object {
"buyer": Object {
"firstName": "firstname",
"lastName": "lastName",
"phoneNumber": "9876543210",
},
"buyerId": "TfHemJat3L3kkz0t3qDn",
"orderDate": "Sat May 29 18:55:47 2021",
"orderDetails": Array [
Object {
"itemId": "3iPDW2OJePJBCuR6xA09",
"status": "Pending",
},
Object {
"itemId": "jDJDHaBLI2kQ4reaaWI8",
"status": "Pending",
},
],
"orderId": "t20212941855550",
}
I want to update the Status from Pending to Accepted where only
ItemId == "3iPDW2OJePJBCuR6xA09".
I don't know how to update, Can you please suggest the solution to the same.
Thank in Advance.
You can use the update function predefined in the firebase library and inside that function pass the argument and variable in which you want to update with the values in the same format as it was created in the database also vote if it works

MongoDB Array Query - Single out an array element

I am having trouble with querying a MongoDB collection with an array inside.
Here is the structure of my collection that I am querying. This is one record:
{
"_id": "abc123def4567890",
"profile_id": "abc123def4567890",
"image_count": 2,
"images": [
{
"image_id": "ABC123456789",
"image_url": "images/something.jpg",
"geo_loc": "-0.1234,11.234567890",
"title": "A Title",
"shot_time": "01:23:33",
"shot_date": "11/22/2222",
"shot_type": "scenery",
"conditions": "cloudy",
"iso": 16,
"f": 2.4,
"ss": "1/545",
"focal": 6.0,
"equipment": "",
"instructions": "",
"upload_date": 1234567890,
"update_date": 1234567890
},
{
"image_id": "ABC123456789",
"image_url": "images/something.jpg",
"geo_loc": "-0.1234,11.234567890",
"title": "A Title",
"shot_time": "01:23:33",
"shot_date": "11/22/2222",
"shot_type": "portrait",
"conditions": "cloudy",
"iso": "16",
"f": "2.4",
"ss": "1/545",
"focal": "6.0",
"equipment": "",
"instructions": "",
"upload_date": 1234567890,
"update_date": 1234567890
}
]
}
Forgive the formatting, I didn't know how else to show this.
As you can see, it's a profile with a series of images within an array called 'images' and there are 2 images. Each of the 'images' array items contain an object of attributes for the image (url, title, type, etc).
All I want to do is to return the object element whose attributes match certain criteria:
Select object from images which has shot_type = "scenery"
I tried to make it as simple as possible so i started with:
find( { "images.shot_type": "scenery" } )
This returns the entire record and both the images within. So I tried projection but I could not isolate the single object within the array (in this case object at position 0) and return it.
I think the answer lies with projection but I am unsure.
I have gone through the MongoDB documents for hours now and can't find inspiration. I have read about $elemMatch, $, and the other array operators, nothing seems to allow you to single out an array item based on data within. I have been through this page too https://docs.mongodb.com/manual/tutorial/query-arrays/ Still can't work it out.
Can anyone provide help?
Have I made an error by using '$push' to populate my images field (making it an array) instead of using '$set' which would have made it into an embedded document? Would this have made a difference?
Using aggregation:
db.collection.aggregate({
$project: {
_id: 0,
"result": {
$filter: {
input: "$images",
as: "img",
cond: {
$eq: [
"$$img.shot_type",
"scenery"
]
}
}
}
}
})
Playground
You can use $elemMatch in this way (simplified query):
db.collection.find({
"profile_id": "1",
},
{
"images": {
"$elemMatch": {
"shot_type": 1
}
}
})
You can use two objects into find query. The first will filter all document and will only get those whose profile_id is 1. You can omit this stage and use only { } if you wnat to search into the entire collection.
Then, the other object uses $elemMatch to get only the element whose shot_type is 1.
Check an example here

How to projection element in array field of MongoDb collection?

MongoDb Collection Example (Person):
{
"id": "12345",
"schools": [
{
"name": "A",
"zipcode": "12345"
},
{
"name": "B",
"zipcode": "67890"
}
]
}
Desired output:
{
"id": "12345",
"schools": [
{
"zipcode": "12345"
},
{
"zipcode": "67890"
}
]
}
My current partial code for retrieving all:
collection.find({}, {id: true, schools: true})
I am querying the entire collection. But I only want to return zipcode part of school element, not other fields (because the actual school object might contain much more data which I do not need). I could retrieve all and remove those un-needed fields (like "name" of school) in code, but that's not what I am looking for. I want to do a MongoDb query.
You can use the dot notation to project specific fields inside documents embedded in an array.
db.collection.find({},{id:true, "schools.zipcode":1}).pretty()

How to convert JSON Http response to Array in AngularJS 2

I'm doing a Http get in Angular 2 and the response is a JSON. However, i'm trying to use this in a ngFor but i can't because it isn't an Array.
How can I convert JSON to Array in Angular 2? I searched in many websites but didn't discover a effective way to do that.
Edit 1:
The response is like that:
{
"adult": false,
"backdrop_path": "/fCayJrkfRaCRCTh8GqN30f8oyQF.jpg",
"belongs_to_collection": null,
"budget": 63000000,
"genres": [
{
"id": 18,
"name": "Drama"
}
],
"homepage": "",
"id": 550,
"imdb_id": "tt0137523",
"original_language": "en",
"original_title": "Fight Club",
"overview": "A ticking-time-bomb insomniac and a slippery soap salesman channel primal male aggression into a shocking new form of therapy. Their concept catches on, with underground \"fight clubs\" forming in every town, until an eccentric gets in the way and ignites an out-of-control spiral toward oblivion.",
"popularity": 0.5,
"poster_path": null,
"production_companies": [
{
"name": "20th Century Fox",
"id": 25
}
],
"production_countries": [
{
"iso_3166_1": "US",
"name": "United States of America"
}
],
"release_date": "1999-10-12",
"revenue": 100853753,
"runtime": 139,
"spoken_languages": [
{
"iso_639_1": "en",
"name": "English"
}
],
"status": "Released",
"tagline": "How much can you know about yourself if you've never been in a fight?",
"title": "Fight Club",
"video": false,
"vote_average": 7.8,
"vote_count": 3439
}
I think if you want to pass from json to array you could do the following command:
var arr = []
for(i in json_object){
arr.push(i)
arr.push(json_object[i])
}
Then you have every keys in the even index and every contents in the odd index
Well, I really don't see the point here. Arrays are for operating with lists of similar objects or types, not for complex structures. If you had a bunch of objects similar to the one you show, then it would make sense. Anyways, if you really want an array then you could do it with recursion and create a flat array of the properties.
var flatPropertyArray = [];
function flatten(obj) {
for (var property in obj) {
if (obj.hasOwnProperty(property)) {
if (typeof obj[property] == "object")
flatten(obj[property]);
else
flatPropertyArray.push(property);
}
}
}
pass your JSON into the flatten func.

How to remove iteams tag from response of google endpoint

I have create an API which is returning the the list of users i want to give the name to that list. by default google endpoint is giving name "items" to the list of object. I want to change this name. Please suggest how can i do this.
{
"items": [
{
"id": 1,
"userTypeID": 1,
"userCurrentLocationID": 0,
"updateBy": 1,
"timeZone": "",
"state": 0,
"postcode": "110085",
"phone": "",
"officeAddressID": 227,
"mobile": "9999999",
"lineManager": "",
"email": "abc#abc.com",
"createdBy": "prbhat.ydav#gmail.com",
"countryID": 1,
"companyID": 227,
"city": "delhi"
}
]
}
If you return List<T> from an Endpoint, it will always name the list in an items field. I believe behind the scenes it's using CollectionResponse so that's why, but my memory is rusty. If you want the name to be something else, simply wrap the list in an object with a different field name. Note that Endpoints requires JSON objects to be returned, so you can't return a JSON array with no wrapping.

Resources