main() {
var i = [{"name" : "123", "item":[{"name": "ssr", "obj":[{"name":"2", "uri": null}]}]}];
print(i[0]["item"]);
//i[0]["item"]["name"] doesn't work!
}
I want to get the value of name of i[0]["item"] and "name" in "obj". how to do that?
Try this:
main() {
var i = [
{
"name": "123",
"item": [
{
"name": "ssr",
"obj": [
{"name": "2", "uri": null}
]
}
]
}
];
var list = i[0]["item"] as List;
print(list[0]["name"]); // ssr
}
Related
I would like to create a Swift TableView for all available sizes of coffee within a specific type. With this JSON tree, how can you structure the class to create an array for the type specific sizes?
The JSON Tree is structured as follows:
{
"_id": "60ba1ab72e35f2d9c786c610",
"types": [
{
"_id": "60ba1a062e35f2d9c786c56d",
"name": "Ristretto",
"sizes": [
"60ba18d13ca8c43196b5f606",
"60ba3368c45ecee5d77a016b"
],
"extras": [
"60ba197c2e35f2d9c786c525"
]
},
{
"_id": "60be1db3c45ecee5d77ad890",
"name": "Espresso",
"sizes": [
"60ba3368c45ecee5d77a016b",
"60ba33dbc45ecee5d77a01f8"
],
"extras": [
"60ba34a0c45ecee5d77a0263"
]
},
{
"_id": "60be1eabc45ecee5d77ad960",
"name": "Cappuccino",
"sizes": [
"60ba18d13ca8c43196b5f606",
"60ba3368c45ecee5d77a016b",
"60ba33dbc45ecee5d77a01f8"
],
"extras": [
"60ba197c2e35f2d9c786c525",
"60ba34a0c45ecee5d77a0263"
]
}
],
"sizes": [
{
"_id": "60ba18d13ca8c43196b5f606",
"name": "Large",
"__v": 0
},
{
"_id": "60ba3368c45ecee5d77a016b",
"name": "Venti"
},
{
"_id": "60ba33dbc45ecee5d77a01f8",
"name": "Tall"
}
],
"extras": [
{
"_id": "60ba197c2e35f2d9c786c525",
"name": "Select the amount of sugar",
"subselections": [
{
"_id": "60ba194dfdd5e192e14eaa75",
"name": "A lot"
},
{
"_id": "60ba195407e1dc8a4e33b5e5",
"name": "Normal"
}
]
},
{
"_id": "60ba34a0c45ecee5d77a0263",
"name": "Select type of milk",
"subselections": [
{
"_id": "611a1adeff35e4db9df19667",
"name": "Soy"
},
{
"_id": "60ba348d8c75424ac5ed259e",
"name": "Oat"
},
{
"_id": "60ba349a869d7a04642b41f4",
"name": "Cow"
}
]
}
]
}
My classes: (I can currently load a TableView with the coffee sizes, but not the type specific sizes)
import Foundation
import UIKit
class Types: Codable {
let types: [CoffeeType]
init(types: [CoffeeType]) {
self.types = types
}
}
class Sizes: Codable {
let sizes: [CoffeeType]
init(sizes: [CoffeeType]) {
self.sizes = sizes
}
}
class CoffeeType: Codable {
let _id: String
let name: String
init(_id: String, name: String) {
self._id = _id
self.name = name
}
}
The app is structured like this: HomeViewController is a TableView of Types. When you click on a Type, you transition to SelectSizeViewController, to which I have already assigned a Type through the segue. On SelectSizeViewController, I would like to display the list of specific sizes.
use QuickType to get the model this is quite helpful. you will be getting the model easily(suggestion). I think you are using the wrong model.
if your Base model struct is correct it should be something like this
struct Coffie: Codable {
let id: String
let types: [TypeElement]
let sizes: [Size]
let extras: [Extra]
enum CodingKeys: String, CodingKey {
case id
case types, sizes, extras
}
}
from here itself you can get the type and sizes with corresponded id's you can filter size values from sizes array
I have one SwiftyJson object.
I can not filter that array. I have tried this solution https://stackoverflow.com/a/37497170/4831567. But my json format is different that's why not working.
[
{
"name": "19860",
"header": {
"start_time": "1519270200",
"end_time": "1519299000",
"state": "lunch"
},
"alerts": "1",
"venue": {
"location": "Delhi, India",
"timezone": "+05:30"
},
"srs_category": [
0,
1
]
},
{
"name": "19861",
"header": {
"start_time": "1519270200",
"end_time": "1519299000",
"state": "Dinner"
},
"alerts": "1",
"venue": {
"location": "Mumbai, India",
"timezone": "+05:30"
},
"srs_category": [
1,
3
]
},
{
"name": "19862",
"header": {
"start_time": "1519270200",
"end_time": "1519299000",
"state": "lunch"
},
"alerts": "1",
"venue": {
"location": "Surat, India",
"timezone": "+05:30"
},
"srs_category": [
0,
2
]
}
]
i want to find that object that srs_category contain 1. I know it is possible by looping and condition. But i want via NSPredicate. If it is possible then please help me.
Thank You.
Here is easy way to use SwiftyJSON:
let filtered = JSON(yourArray).arrayValue.filter({
$0["srs_category"].arrayValue.map({ $0.intValue }).contains(1)
})
Use a Swift native function rather than NSPredicate
data represents the Data object received from somewhere
do {
if let json = try JSONSerialization.jsonObject(with:data) as? [[String:Any]] {
let srsCategory1 = json.first(where: { dict -> Bool in
guard let array = dict["srs_category"] as? [Int] else { return false }
return array.contains(1)
})
print(srsCategory1 ?? "not found")
}
} catch {
print(error)
}
If there are multiple items which can match the condition replace first with filter. Then the result is a non-optional array.
I Post one Json with RestAssured and After I need to verify that all fields are stored in the database with the correct values.My Json is :
{
"id": "1",
"name": "name1",
"description": "description1",
"source": "source1",
"target": "target1",
"domain": "PM",
"transformation_rules": [
{
"name": "name2",
"filters": [
{
"object": "object1",
"pattern": "pattern1"
}
],
"operations": [
{
"pattern": "pattern2",
"replacement": "replacement1"
}
]
},
{
"name": "name3",
"filters": [
{
"object": "object2",
"pattern": "pattern2"
}
],
"operations": [
{
"pattern": "pattern3",
"replacement": "replacement2"
},
{
"pattern": "pattern3",
"replacement": "replacement3"
},
{
"pattern": "pattern4",
"replacement": "replacement4"
}
]
}
],
"conflict_policy": "ACCEPT_SOURCE"
}
So, I have :
responseGet = RestAssured.given().contentType(ContentType.JSON).when().get(urlApi + "/" + id);
My first verification is :
responseGet.then().body("$[0]['id']", equalTo("1"));
to verify that the field "id" equals to 1 it doesn't execute well and I change to :
responseGet.then().body("$.id", equalTo("1"));
and the same result ---> fails
Please, can you give me your suggestions for testing all the Json ?
Just for information, I try to apply : https://github.com/json-path/JsonPath.
Thank you very much in Advance,
Best Regards,
You can directly use jsonPath() for checking this:
For example:
responseGet.body().jsonPath().getString("id").equals("1");
For reading JsonPath
I have the following structure:
"countries": [
{
"states" :[
{
"name" :"Texas",
"id": "a1"
},
{
"name" :"Nebraska",
"id": "a1"
}
]
},
{
"states" :[
{
"name" :"New York",
"id": "a1",
},
{
"name" :"Florida",
"id": "a1"
}
]
}
]
I want to return an array of all the states from above.
Here is what I tried:
countries.map { |country| country.states.map { |state| state.name } }
But it returns only the first 2 statest 'Texas' and Nebraska.
Can someone tell me what I am doing wrong here?
you structure wasn't right, so corrected:
countries = [
{
"states" => [
{
"name" => "Texas",
"id"=> "a1"
},
{
"name"=> "Nebraska",
"id"=> "a1"
}
]
},
{
"states" => [
{
"name"=> "New York",
"id"=> "a1",
},
{
"name" =>"Florida",
"id"=> "a1"
}
]
}
]
Ruby wasn't accepting ":" for strings for some weird reasons. Like this(which isn't working):
countries = [
{
"states": [
{
"name": "Texas",
"id": "a1"
},
{
"name": "Nebraska",
"id": "a1"
}
]
},
{
"states": [
{
"name": "New York",
"id": "a1",
},
{
"name" :"Florida",
"id": "a1"
}
]
}
]
For this, you can do:
countries.map{ |c| c["states"].map{|s| s["name"]}}.flatten
#=> ["Texas", "Nebraska", "New York", "Florida"]
Or if you get the repetitive values then:
countries.map{ |c| c["states"].map{|s| s["name"]}}.flatten.uniq
#=> ["Texas", "Nebraska", "New York", "Florida"]
I hope this helps.
Go for Surya's answer, it is the same solution. Just wanna show how I write it:
countries.map{|x|x['states']}
.flatten
.map{|x|x['name']}
i am trying to parse the following json
{
"offerinfo": {
"offername": "chaos",
"offertype": "3",
"brand": "1",
"subbrand": "0",
"categories": "1,2",
"Tags": "4,6",
"promotiontype": "1",
"currency": "1",
"promotioncode": "1",
"offertitle": "1",
"offerdescription": "ad",
"addtionalterms": "asdasd",
"retaildescription": "asdasd"
},
"media": {
"video": "",
"images": []
},
"availability": [
{
"airports": "1,4,6",
"stores": "3,4,5",
"startdate": "2014",
"enddate": "3434"
}],
"featured": {
"categories": "",
"slot": ""
}
}
COde for parsing is
$json = json_decode(trim(file_get_contents('php://input')),true);
//print_r($json)."<br/>";
//var_dump($json);
foreach($json as $key=>$value)
{
var_dump($value);
$offername = $value['offername']."<br/>";
//echo $media = $value['video'];
$mediaimage = $value['images'];
foreach($mediaimage as $a)
{
//echo $a['MediaFile'];
}
//echo $avail = $value['airports'];
echo $key->{'availability'};
//var_dump($avail);
// foreach($avail as $b)
// {
// echo $b['airports'];
//}
//var_dump($mediaimage);
}
i got the offername etc those in ogger info dictionary, but i am unable to parse the information from availability
can some one kindly help me
$json['availability'] is an array so you can access it like this
foreach ($json['availability'] as $availability) {
echo $availability["airports"];
// etc
}