How to parse a nested json array in CI - foreach

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
}

Related

dart get object value in array of array

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
}

elasticsearch with painless script to return extra fields

I am following this example https://www.compose.com/articles/how-to-script-painless-ly-in-elasticsearch/
where BOTH the ORIGINAL fields plus the calculated field (some_scores) are presented in the result document.
{
"_index": "sat",
"_type": "scores",
"_id": "AV3CYR8JFgEfgdUCQSON",
"_score": 1,
"_source": {
"cds": 1611760130062,
"rtype": "S",
"sname": "American High",
"dname": "Fremont Unified",
"cname": "Alameda",
"enroll12": 444,
"NumTstTakr": 298,
"AvgScrRead": 576,
"AvgScrMath": 610,
"AvgScrWrit": 576,
"NumGE1500": 229,
"PctGE1500": 76.85,
"year": 1516
},
"fields": {
"some_scores": [
1152
]
}
}
Now i am doing a _search with the following post body
{
"query": {
"match_all": {}
},
"script_fields": {
"some_scores": {
"script": {
"lang": "painless",
"inline": "\"hello\""
}
}
}
}
but the results i am getting DOESN'T contain the original fields; it only contains the testing field which i hardcoded to hello. Is there anything wrong with my query ?
"hits": [
{
"_index": "abcIndex",
"_type": "data",
"_id": "id_00000025",
"_score": 1.0,
"fields": {
"some_scores": [
"hello"
]
}
}]
You need to explicitly pass _source": ["*"] when using script field.
I was not able to find reason for this , looks like some kind of optimization.
{
"_source": ["*"],
"query": {
"match_all": {}
},
"script_fields": {
"some_scores": {
"script": {
"lang": "painless",
"inline": "doc['authorization']+\"hello\""
}
}
}

How do take the values from a large JSON response with multiple arrays and brackets?

I have a JSON response (over 500lines) , that has several arrays and brackets inside. Basically an overly nested response.
I am using Alamofire for fetching and i get a JSONData as response. But I don't know how to take values from the response and print it on a custom cell .
I am using Alamofire 5 to get the JSON response.
Please excuse if this sounds too newbieish , I am new to iOS developing.
{
"availabilityResultList": [
{
"availabilityRouteList": [
{
"availabilityByDateList": [
{
"originDestinationOptionList": [
{
"fareComponentGroupList": [
{
"boundList": [
{
"availFlightSegmentList": [
{
"addOnSegment": false,
"flightSegment": {
"journeyDuration": "PT1H15M",
"distance": 1,
"departureAirport": {
"locationName": "LOC",
"cityInfo": {
"country": {
"locationName": "LOC",
"currency": {
"code": "USD"
},
"locationCode": "LOC",
"locationNameLanguage": "EN"
},
"city": {
"locationName": "LOC",
"locationCode": "LOC",
"locationNameLanguage": "EN"
}
},
"codeContext": "ASD",
"language": "EN",
"locationCode": "LOC"
},
"equipment": {
"airEquipType": "ABC",
"changeofGauge": false
},
"remark": "NO",
"ticketType": "PP",
"onTimeRate": 0,
"flightNotes": [
{
"deiCode": 0
}
],
"flightSegmentID": "",
"flownMileageQty": 0,
"flightNumber": "106",
"groundDuration": "",
"trafficRestriction": {
"code": "",
"explanation": {}
},
"stopQuantity": 0,
"codeshare": false,
"secureFlightDataRequired": false,
"departureDateTime": {
"month": 5,
"hour": 6,
"year": 2019,
"timezone": 270,
"day": 6,
"minute": 45,
"second": 0
},
"ondControlled": false,
"arrivalDateTime": {
"month": 5,
"hour": 8,
"year": 2019,
"timezone": 270,
"day": 6,
"minute": 0,
"second": 0
},
"airline": {
"code": "RQ"
},
"arrivalAirport": {
"locationName": "LOC",
"cityInfo": {
"country": {
"locationName": "AA",
"currency": {
"code": "USD"
},
"locationCode": "AA",
"locationNameLanguage": "EN"
},
"city": {
"locationName": "loc",
"locationCode": "LOC",
"locationNameLanguage": "EN"
}
},
"codeContext": "ASD",
"language": "EN",
"locationCode": "LOC"
},
"sector": "ASD",
"accumulatedDuration": ""
},
"marriageGroup": "-1"
}
],
"boundCode": "Outbound"
}
]
}
]
},
JSON is a very simple format and easy to read. There are only two different collection types and four value types.
{} is a dictionary and is subscripted by key
[] is an array and is subscripted by index (zero-based)
Everything in double quotes is String, even "123" and "false"
false and true is Bool
Numeric values are Double, without fractional digits Int
<null> is NSNull
With SwiftyJSON you get distance in flightSegment with (root represents the top level object`)
root["availabilityResultList"][0]["availabilityRouteList"][0]["availabilityByDateList"][0]["originDestinationOptionList"][0]["fareComponentGroupList"][0]["boundList"][0]["availFlightSegmentList"][0]["flightSegment"]["distance"]

"Invalid JSON payload received." when creating a new sheet

I'm just starting out with the Sheets API, and I'm following this setup to create a new sheet: https://developers.google.com/sheets/api/reference/rest/v4/spreadsheets/create
In this code, the spreadsheetBody object is empty. For this I've used the example on this page: https://developers.google.com/sheets/api/samples/writing and added this code to the spreadsheetBody variable:
{
"range": "Sheet1!A1:D5",
"majorDimension": "ROWS",
"values": [
["Item", "Cost", "Stocked", "Ship Date"],
["Wheel", "$20.50", "4", "3/1/2016"],
["Door", "$15", "2", "3/15/2016"],
["Engine", "$100", "1", "30/20/2016"],
["Totals", "=SUM(B2:B4)", "=SUM(C2:C4)", "=MAX(D2:D4)"]
],
}
However, when I post this I get the error "Invalid JSON payload received. Unknown name "range" at 'spreadsheet': Cannot find field.". What might be wrong here?
The request body you are using is for spreadsheets.values.update.
As a sample, the request body for creating Spreadsheet is as follows. In this sample request body, ["Item", "Cost", "Stocked", "Ship Date"], ["Wheel", "$20.50", "4", "3/1/2016"] was used from the document you use.
Sample request body:
{
"properties":
{
"title": "sampleSpreadsheet"
},
"sheets":
[
{
"data":
[
{
"startRow": 0,
"startColumn": 0,
"rowData":
[
{
"values":
[
{
"userEnteredValue":
{
"stringValue": "Item"
}
},
{
"userEnteredValue":
{
"stringValue": "Cost"
}
},
{
"userEnteredValue":
{
"stringValue": "Stocked"
}
},
{
"userEnteredValue":
{
"stringValue": "Ship Date"
}
}
]
},
{
"values":
[
{
"userEnteredValue":
{
"stringValue": "Wheel"
}
},
{
"userEnteredValue":
{
"numberValue": 20.5
},
"userEnteredFormat":
{
"numberFormat":
{
"type": "NUMBER",
"pattern": "$##.00"
}
}
},
{
"userEnteredValue":
{
"numberValue": 4
}
},
{
"userEnteredValue":
{
"numberValue": 42372
},
"userEnteredFormat":
{
"numberFormat":
{
"type": "DATE",
"pattern": "d/m/yyyy"
}
}
}
]
}
]
}
]
}
]
}
Note:
When this request body is used for spreadsheets.create, a Spreadsheet with the filename of sampleSpreadsheet is created. The sheet has the values of ["Item", "Cost", "Stocked", "Ship Date"], ["Wheel", "$20.50", "4", "3/1/2016"] at "A1:D2".
References:
spreadsheets.create- spreadsheets.batchUpdate

Filter Data in SwiftyJson

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.

Resources