How can I convert json map to List String? - list

I need to get country name and country code into List as "Andorra (AD)". I can load json to a map but I cannot convert to List. How can I convert json map to List String?
"country": [
{
"countryCode": "AD",
"countryName": "Andorra",
"currencyCode": "EUR",
"isoNumeric": "020"
},

You can use the .map() function
var countryList = country.map((c) => '${c["countryName"]} (${c["countryCode"]})').toList()

Related

How to perform a search in array of object flutter?

I am having a Map list with key and values, for example :
map<String, dynamic> my_List = [{"name": "mike", "age": "20"}, {"name":"william","age": "23"}].
I already tried containsValue but I don't want to use it.
The result i need to get is, when i search for m i need to get [{"name": "mike", "age": "20"}, {"name":"william","age": "23"}] , and when i search 3 i need the result as [{"name":"william","age": "23"}].
You could create a Person or User class as julemand101 has suggested but if You have to work with Map try this:
List<Map<String, dynamic>> search(String input){
return my_List.where((e) => e["name"].contains(input) || e["age"].contains(input)).toList();
}

How to extract values from JSON response in Postman?

I have a JSON Response :
[{
"dateTime": 1603650600000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454687,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603650600000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573993,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Orange GP ",
"gender": "male",
"supplierId": "788",
"appointmentId": 454688,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}, {
"dateTime": 1603651500000,
"supplierName": "Mr Kennedy test ",
"gender": "male",
"supplierId": "600",
"appointmentId": 573994,
"tentativeAppointmentCode": "5f8ff4a8a9d5f"
}]
I need to extract the values of first occurrence of dateTime, AppointmentId and tentativeAppointmentCode.
Tried below mentioned code but didn't work in this case.
var jsonData=JSON.parse(responseBody);
postman.setEnvironmentVariable("dateTime",jsonData.dateTime);
How can I extract these values and store in a variable so that I can use it in other requests?
Assuming, by "reservation ID" you mean tentativeAppointmentCode (reservation ID doesn't occur in your response body), the following will do it:
let jsonData = pm.response.json();
pm.environment.set("dateTime",jsonData[0].dateTime);
pm.environment.set("appointmentId",jsonData[0].appointmentId);
pm.environment.set("tentativeAppointmentCode",jsonData[0].tentativeAppointmentCode);
I have done something like this for storing a token for later use
const jsonData = pm.response.json();
pm.environment.set("token", jsonData.access_token);

how to extract data inside the list of maps and convert it into maps in dart

How can extract data inside the list of maps and convert it into maps in the dart.
Like I have a List of maps ================================================================================================================================================================================================
[
{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
,{"business_id":"2",
"business_title":"Spotify",
"business_phone":"(055) 3733783",
"business_email":"Usamashafiq309#gmail.com",
"business_website":"www.spotify.com",
"business_address":"Spotify AB, Regeringsgatans bro, Stockholm, Sweden",
"business_address_longitude":"18.0680873",
"business_address_latitude":"59.33096949999999",
"business_image":"5f84c7a4bbbd0121020201602537380.png",
"business_created_at":"2020-10-20 15:40:17",
"business_category_id":"2",
"cat_id":"2",
"cat_title":"Gym",
"cat_image":"280920201601308237.png"}
]
and convert it like this
[ {"business_id":"2",
"business_title":"Spotify",},
{"business_id": "1",
"business_title": "Pizza Hut",},
]
You can use the map function to apply a function to each element of a list. Then you can create a submap with your map.
Here is a quick exemple:
void main() async {
List l = [
{
"business_id": "2",
"business_title": "Spotify",
"business_phone": "(055) 3733783",
},
{
"business_id": "1",
"business_title": "Pizza Hut",
"business_phone": "(055) 9999999",
}
];
print(extractMap(l));
}
List extractMap(List l) {
return l
.map((element) => Map.fromEntries([
MapEntry('business_id', element['business_id']),
MapEntry('business_title', element['business_title']),
]))
.toList();
}

How to get JSONobject from JSONArray in postman

I am trying to automize a registration scenario in postman using test scripts
I have the following JsonArray as a response:
[
{
"id": 1,
"name": "user_A",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_A#gmail.com"
"street": "str. 0001",
"city": "DEF",
}
......
......
......
{
"id": 4,
"name": "user_B",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_B#gmail.com"
"street": "str. 0002",
"city": "NJ",
}
......
......
......
{
"id": 10,
"name": "User_C",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_C#gmail.com"
"street": "str. 0003",
"city": "ABC",
}
......
]
the array length can be dynamic and changed (in this sample is 10) and want to find the object with special email (somewhere in the array) and then get the ID from that object and make the assertion based on JsonData from this object (catch elements e.g. check name).
how can I do that?
thanks for the support.
I send a GETrequest to get all Data from Registration DB.
as response I get a JsonArray
from Json Array I need the specific Object for the assertion (e.g. object with email user_B in sample) .
I know my Email address and base on it I have to findout the ID from Object .
I can do it when I know which ID is my ID but in case it is dynamic I don't know how to search an array for it in postman to get ID
For example, to assert the company name
pm.expect(jsonData[0].company).to.equal(pm.environment.get("regDB_new_company"))
but if I dont know the ID ( only know my email) I have first to find out the ID of Object then I can asser it.
e.g.
in this case first, find the object with email "user_B#gmail.com"
then from that object get ID element (in this case 4)
then I want to assert for all data from the object
Thanks Danny, I found the solution
var arr = pm.response.json()
for(i = 0; i < arr.length; i++) {
if (arr[i].email == "userB#gmail.com") {
pm.environment.set("personID", arr[i].id)
}
}

How to set an Array<Object> inside a Dictionary<String, AnyObject> - Swift3

I'm new in swift. I'm trying to add an Array to a specific key in my Dictionary.
I have the following code:
var myArray : Array<Links> = []
var myDict : Dictionary<String, AnyObject> = [:]
myDict["links"] = myArray as AnyObject? // I need help in this row, It does not work.
This is the Json structure I have in myDict and I'm trying to set:
id : "blabla"
links: [
0: {key1: "a", key2: "b", name: "c", link: "d"}
1: {key1: "e", key2: "f", name: "j", link: "h"}
]
Please, consider I already have all the rest working properly. My only problem is how to add my array in the dictionary as commented in the code above.
My JSON structure:
I hope I could make myself clear enough.
Thank you.
First of all don't cast types up and don't annotate types unless the compiler complains.
Second of all a JSON dictionary is [String:Any] in Swift 3.
Further the recommended syntax to create an empty collection object is
var myDict = Dictionary<String, Any>()
Assuming your array – actually a dictionary – is
let myArray = [
0: ["key1": "a", "key2": "b", "name": "c", "link": "d"],
1: ["key1": "e", "key2": "f", "name": "j", "link": "h"]
]
just assign it:
myDict["links"] = myArray
Even if there is a struct
struct Link {
var key1, key2, name, link : String
}
and the array dictionary is
let linkDictionary = [
0: Link(key1:"a", key2: "b", name: "c", link: "d"),
1: Link(key1:"e", key2: "f", name: "g", link: "h")]
you can assign it if the value type is Any
myDict["links"] = linkDictionary
Assuming, for a second, that links really was an array, it would be:
var dictionary: [String: Any] = [
"id": "blabla",
"links": [
["key1": "a", "key2": "b", "name": "c", "link": "d"],
["key1": "e", "key2": "f", "name": "j", "link": "h"]
]
]
// retrieve links, or initialize it if not found
var links = dictionary["links"] as? [[String: String]] ?? [[String: String]]()
// add your new link to local dictionary
links.append(["key1": "k", "key2": "l", "name": "m", "link": "n"])
// update original structure
dictionary["links"] = links
Personally, though, when I see a repeating dictionary structure like your links, this screams for a real model for these objects. For example:
struct Foo {
let id: String
var links: [Link]?
}
struct Link {
let key1: String
let key2: String
let name: String
let link: String
}
var foo = Foo(id: "blabla", links: [
Link(key1: "a", key2: "b", name: "c", link: "d"),
Link(key1: "e", key2: "f", name: "j", link: "h")
])
foo.links?.append(Link(key1: "k", key2: "l", name: "m", link: "n"))
Now, in this latter example, I assumed that links was really an array, not a dictionary, but that's not really my point here. My key observation is that code is more readable and robust if you use proper custom types rather than just arrays and dictionaries.
And if you need to send and receive these model objects to some web service, you then map this model object to and from JSON. But use custom types for your actual model.
If you want to make the above types easily converted to and from JSON, you can use one of the object mapping libraries out there, so you can do something yourself, e.g.:
protocol Jsonable {
var jsonObject: Any { get }
init?(jsonObject: Any)
}
extension Foo: Jsonable {
var jsonObject: Any {
return [
"id": id,
"links": links?.map { $0.jsonObject } ?? [Any]()
]
}
init?(jsonObject: Any) {
guard let dictionary = jsonObject as? [String: Any],
let id = dictionary["id"] as? String else { return nil }
var links: [Link]?
if let linksDictionary = dictionary["links"] as? [Any] {
links = linksDictionary.map { Link(jsonObject: $0)! }
}
self.init(id: id, links: links)
}
}
extension Link: Jsonable {
var jsonObject: Any { return [ "key1": key1, "key2": key2, "name": name, "link": link ] }
init?(jsonObject: Any) {
guard let dictionary = jsonObject as? [String: Any],
let key1 = dictionary["key1"] as? String,
let key2 = dictionary["key2"] as? String,
let name = dictionary["name"] as? String,
let link = dictionary["link"] as? String else {
return nil
}
self.init(key1: key1, key2: key2, name: name, link: link)
}
}
Then you can do stuff like:
let object = try JSONSerialization.jsonObject(with: data)
var foo = Foo(jsonObject: object)!
Or:
foo.links?.append(Link(key1: "j", key2: "k", name: "l", link: "m"))
let data = try! JSONSerialization.data(withJSONObject: foo.jsonObject)
This was the solution:
var arrLinks : Array<Dictionary<String, Any>> = []
for link in myArray {
var dict : Dictionary<String, Any> = [:]
dict["key1"] = link.name
dict["key2"] = link.ghostBefore
dict["key3"] = link.ghostAfter
arrLinks.append(dict)
}
myDict["links"] = arrLinks as AnyObject