Json parsing wrong in IOS - iphone

Hi i have some problem parsing the json in IOS. This is the json data.
{
"app_info": [
{
"app_name": "haka",
"sync_protocol_version": "1"
}
],
"updates": [
{
"timestamp": "Sat Apr 21 13:04:08 IST 2012",
"people": [
{
"personal_info": [
{
"first_name": "phlox",
"last_name": "",
"employee_id": "010",
"gender": "-",
"marital_status": "-",
"nationality": "Denobulan",
"dob": "re-23",
"photo": "http://c.cc/users/010/profile/image"
}
],
"contact_details": [
{
"address": [
{
"street": "#1, this way",
"city": "tank",
"state": "sick bay",
"zip": "0978",
"country": "Enterprise"
}
],
"telephone": [
{
"work": "010",
"mobile": "010",
"home": "010"
}
],
"email": [
{
"work": "phlox#nx-10.ent",
"personal": ""
}
]
}
],
"emergency": [
{
"contact": [
{
"name": "-",
"relationship": "",
"telephone": [
{
"work": "",
"home": "",
"mobile": ""
}
]
}
],
"blood_group": ""
}
],
"categorization": [
{
"designation": "",
"department": "",
"location": "",
"joining_date": ""
}
]
},
{
"personal_info": [
{
"first_name": "",
"last_name": "",
"employee_id": "",
"gender": "",
"marital_status": "",
"nationality": "",
"dob": "",
"photo": ""
}
],
"contact_details": [
{
"address": [
{
"street": "",
"city": "",
"state": "",
"zip": "",
"country": ""
}
],
"telephone": [
{
"work": "",
"mobile": "",
"home": ""
}
],
"email": [
{
"work": "",
"personal": ""
}
]
}
],
"emergency": [
{
"contact": [
{
"name": "",
"relationship": "",
"telephone": [
{
"work": "",
"home": "",
"mobile": ""
}
]
}
],
"blood_group": ""
}
],
"categorization": [
{
"designation": "",
"department": "",
"location": "",
"joining_date": ""
}
]
}
],
"messages": [
{
"sender": "Archer<admin#nx-10.ent>",
"sender_role": "admin",
"message_type": "broadcast",
"message": "parking space up for grabs",
"message_recipients": "all",
"reply_permitted": "0"
}
],
"events": [
{
"creator": "Travis<ensign#nx-01.ent>",
"event_title": "",
"event_description": "",
"event_time_start": "",
"event_time_end": "",
"location": "",
"invitees": [
{
"id": "020",
"acceptance": "1"
}
]
}
],
"settings": [
{
"sync_frequency": "0"
}
]
}
]}
This is a valid json format. I have checked it with http://jsonlint.com/ and using http://braincast.nl/samples/jsoneditor/
see the structure of json value.According to structure the people tag should return count of 2, as it has 2 objects, but it is returning only 1 while parsing.
I am completely out of options. Please help guys.
This is the code i am using for parsing
NSString *textPAth = [[NSBundle mainBundle] pathForResource:#"sync" ofType:#"json"];
NSError *error;
NSString *content = [NSString stringWithContentsOfFile:textPAth encoding:NSUTF8StringEncoding error:&error];
NSArray *jsonArray = [[content JSONValue] retain];
NSLog(#"JSON ARRAY %# AND COUNT %d",[[jsonArray valueForKey:#"updates"] valueForKey:#"people"],[[[jsonArray valueForKey:#"updates"] valueForKey:#"people"] count]);

I'm not sure why every dictionary is wrapped with an array, when there is only 1 entry (unnecessary), but if you want to parse it you'd want something like this:
NSDictionary *jsonDict = [[content JSONValue] retain];
NSArray *updatesArray = [jsonDict objectForKey:#"updates"];
NSDictionary *updatesDict = [updatesArray objectAtIndex:0];
NSArray *peopleArray = [updatesDict objectForKey:#"people"];
NSLog(#"People count: %i", [peopleArray count]);
for (NSDictionary *peopleDict in peopleArray) {
//do something
}
As a side note, if this is your JSON, you'll want to remove the [arrays] for entries that are not actually arrays. While you can still parse it, it means you'll have to read the array first then get the dictionary from the objectAtIndex:0, which is totally inefficient and pointless.

Could it be that every one of your objects is wrapped in an array and giving unexpected results?

Related

can't able to store fhir resource in mongodb using asymmetrik mongodb fhir-core-server

i'm running node-fhir-server-mongo(Asymmetrik github repo)..when i put resource using PUT method and it stores in mongodb...everything works fine...but the data is partially stored...when i try to access the data i stored in database it only shows few pieces only...
below code is the data i want to store..
{
"resourceType": "Patient",
"id": "example3",
"text": {
"status": "generated",
},
"identifier": [
{
"use": "usual",
"type": {
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0203",
"code": "MR"
}
]
},
"system": "urn:oid:1.2.36.146.595.217.0.1",
"value": "12345",
"period": {
"start": "2001-05-06"
},
"assigner": {
"display": "Acme Healthcare"
}
}
],
"active": true,
"name": [
{
"use": "official",
"family": "Chalmers",
"given": [
"Peter",
"James"
]
},
{
"use": "usual",
"given": [
"Jim"
]
},
{
"use": "maiden",
"family": "Windsor",
"given": [
"Peter",
"James"
],
"period": {
"end": "2002"
}
}
],
"telecom": [
{
"use": "home"
},
{
"system": "phone",
"value": "(03) 5555 6473",
"use": "work",
"rank": 1
},
{
"system": "phone",
"value": "(03) 3410 5613",
"use": "mobile",
"rank": 2
},
{
"system": "phone",
"value": "(03) 5555 8834",
"use": "old",
"period": {
"end": "2014"
}
}
],
"gender": "male",
"birthDate": "1974-12-25",
"_birthDate": {
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/patient-birthTime",
"valueDateTime": "1974-12-25T14:35:45-05:00"
}
]
},
"deceasedBoolean": false,
"address": [
{
"use": "home",
"type": "both",
"text": "534 Erewhon St PeasantVille, Rainbow, Vic 3999",
"line": [
"534 Erewhon St"
],
"city": "PleasantVille",
"district": "Rainbow",
"state": "Vic",
"postalCode": "3999",
"period": {
"start": "1974-12-25"
}
}
],
"contact": [
{
"relationship": [
{
"coding": [
{
"system": "http://terminology.hl7.org/CodeSystem/v2-0131",
"code": "N"
}
]
}
],
"name": {
"family": "du Marché",
"_family": {
"extension": [
{
"url": "http://hl7.org/fhir/StructureDefinition/humanname-own-prefix",
"valueString": "VV"
}
]
},
"given": [
"Bénédicte"
]
},
"telecom": [
{
"system": "phone",
"value": "+33 (237) 998327"
}
],
"address": {
"use": "home",
"type": "both",
"line": [
"534 Erewhon St"
],
"city": "PleasantVille",
"district": "Rainbow",
"state": "Vic",
"postalCode": "3999",
"period": {
"start": "1974-12-25"
}
},
"gender": "female",
"period": {
"start": "2012"
}
}
],
"managingOrganization": {
"reference": "Organization/1"
} }
and the actual data is stored on the mongodb is....
_id: "example3" id: "example3" meta: Object versionId: "1" lastUpdated: "2022-06-28T08:44:44+00:00" resourceType: "Patient"
if anyone know the answer or how to solve please let me know....thanks in advance!

mongodb select all fields which is not null or empty string

I have mongodb document which has data like this:
{
"_id": "ObjectId(\"5e09db41d4ccee7f500f7326\")",
"time": "ISODate(\"2019-12-30T09:10:53Z\")",
"syslog_fac": 23,
"syslog_sever": 6,
"syslog_tag": "",
"procid": "",
"pid": "-",
"status": "Allowed",
"logtype": "Firewall Logs",
"date": "2019-12-30",
"Module": "01UM",
"Desc": "Theuserloggedout.(UserName",
"Severity_Level": "6",
"Vsys": "public",
"SourceIP": "10.10.0.57",
"ParentGroup": "/netgrup.com.tr",
"LogonTime": "2019/12/3014:07:20",
"LogoutTime": "2019/12/3014:10:53",
"ObversePackets": "0",
"ObverseBytes": "0",
"ReversePackets": "0",
"ReverseBytes": "0",
"LogoutReason": "AnIPaddressconflictoccurred",
"VSys": "",
"PolicyName": "",
"Country": "",
"DestinationIP": "",
"SourcePort": "",
"DestinationPort": "",
"SourceZone": "",
"DestinationZone": "",
"User": "",
"Protocol": "",
"ApplicationName": "",
"Profile": "",
"Type": "",
"Category": "",
"SubCategory": "",
"Page": "",
"Host": "",
"Referer": "",
"Item": "",
"Action": "",
"level": "",
"SourceNatIP": "",
"SourceNatPort": "",
"BeginTime": "",
"EndTime": "",
"SendPkts": 0,
"SendBytes": 0,
"RcvPkts": 0,
"RcvBytes": 0,
"SourceVpnID": "",
"DestinationVpnID": "",
"CloseReason": "",
"Task": "",
"Ip": "",
"VpnName": "",
"AuthenticationMethod": "",
"Command": "",
"user-name": "",
"attack-type": "",
"interface": "",
"packet-count": "",
"rate-number": "",
"file-name": "",
"file-type": "",
"direction": "",
"detect-type": "",
"virus-name": "",
"signature-id": "",
"event-number": "",
"target": "",
"role": "",
"user": ""
}
As you see there are a lot of fields which have an empty string or 0 , so what I want to do is to select only columns that have value except 0 or empty string.
this is my code that I am using to execute query from laravel but return nothings , when I apply that code in mongo directly I get correct data , and return exactly what I want , but return nothings from laravel ,
$data = Logss::raw(function($collection)use ($_id)
{
return $collection->aggregate([
[ '$match' => ['_id'=>'ObjectId(5e09dc63715d622be622c639)']],
[
'$replaceRoot'=> [
'newRoot'=>[
'$arrayToObject'=>[
'$filter'=> [
'input'=> [ '$objectToArray'=>'$$ROOT' ],
'cond'=> [
'$and'=> [
[ '$ne'=> [ '$$this.v', "" ] ],
[ '$ne'=>[ '$$this.v', 0 ] ]
]
]
]
]
]
]
]
]);
});
You can run below query:
db.collection.aggregate([
{ $match: { _id: ObjectId(...) } },
{
$replaceRoot: {
newRoot: {
$arrayToObject: {
$filter: {
input: { $objectToArray: "$$ROOT" },
cond: {
$and: [
{ $ne: [ "$$this.v", "" ] },
{ $ne: [ "$$this.v", 0 ] }
]
}
}
}
}
}
}
])
The idea is pretty simple: you start with $objectToArray to get all the fields as an array. Then you can run $filter to remove all zeros and whitespaces and convert that array back to an object $arrayToObject promoting it to the root level ($replaceRoot).
Mongo Playground

Not picking Index - when querying Object -> array -> Object in N1QL

Index not picking when using N1QL to match all the customers belonging to a country
Note : the bucket has around 10 lack records, the document is fetching after 50 seconds,
query
select * from `user-prof` WHERE ANY item IN devices.location SATISFIES item.country IN ["US"]
index
CREATE INDEX id_userProfile ON `user-prof` ( ALL ARRAY v.country FOR v IN devices.location END )
Document
[
{
"customers": {
"devices": {
"user": "u1",
"custid": "14CE5534CCE",
"token": "4D5BE85896833148D696A1397C",
"guest": {
"lastActive": null,
"searches": [
]
},
"latt": "6655059908",
"locale": "en-US",
"location": [
{
"city": "Afc",
"country": "IN"
},
{
"city": "Newyork",
"country": "US"
},
{
"city": null,
"country": null
}
],
"long": "4.21787927806",
"notify": {
"Stats": false
},
"tier": null,
"tmz": "EU",
"version": "0.1"
}
}
},
{
"customers": {
"devices": {
"user": "u2",
"custid": "64CE5534CC1E",
"token": "6D5BE85896833148D696A1397C",
"guest": {
"lastActive": null,
"searches": [
]
},
"latt": "6655059908",
"locale": "en-US",
"location": [
{
"city": "Texas",
"country": "US"
},
{
"city": null,
"country": null
}
],
"long": "4.21787927806",
"notify": {
"Stats": false
},
"tier": null,
"tmz": "EU",
"version": "0.1"
}
}
}
You are using Pre 4.6.2 The variable in the ANY clause needs to be same as the variable in the CREATE INDEX (i.e item ,v )
https://developer.couchbase.com/documentation/server/current/n1ql/n1ql-language-reference/indexing-arrays.html

Parse combination of json nested objects and arrays

[
{
"Profile": {
"id": "13",
"user_id": "13",
"first_name": "samm",
"profile_image": "13-IMG_169.png",
"where_from": "abro",
"where_live": "simba",
"age": "24",
"profile_type": null,
"company_name": "nick",
"job_title": "developer",
"industry": "software",
"education": "bscs",
"what_you_do": "developement",
"detail_summery": "summary",
"location": null,
"state_id": "1",
"city_id": "84",
"favorite_music_bands": "",
"favorite_teams": "",
"favorite_books": "",
"favorite_movies": null,
"small_intro": "developer"
}
}
],
{
"LookingData": [
{
"user_looking_id": "675",
"looking_id": "1",
"looking_text": "Expand Professional network"
},
{
"user_looking_id": "456",
"looking_id": "2",
"looking_text": "Prospect new business / sales"
},
{
"user_looking_id": "453",
"looking_id": "3",
"looking_text": "Share trade expertise / stories"
},
{
"user_looking_id": "123",
"looking_id": "5",
"looking_text": "Recruitment"
},
{
"user_looking_id": "654",
"looking_id": "6",
"looking_text": "Seeking business partner"
},
{
"user_looking_id": "123",
"looking_id": "7",
"looking_text": "Advise"
}
]
},
{
"MusicData": [
{
"user_music_id": "54",
"music_id": "2",
"music_name": "Country"
}
]
},
{
"SportData": [
{
"user_sport_id": "234",
"sport_id": "4",
"sport_name": "Hockey"
}
]
},
{
"HobbyData": []
},
[],
{
"MovieData": [
{
"user_movie_id": "645",
"movie_id": "6",
"movie_name": "Drama"
}
]
},
[],
{
"CarrerData": [
{
"user_carrer_id": "34",
"carrer_id": "2",
"carrer_name": "Marketing"
},
{
"user_carrer_id": "645",
"carrer_id": "8",
"carrer_name": "Sales"
}
]
}
]
get json Array using this line...
NSDictionary *responseDict = [NSJSONSerialization JSONObjectWithData:data //1
options:0
error:&error];
and get profile data using for loop...
for (NSDictionary *obj in [responseDict valueForKey:#"Profile"])
{
model.userProfileObj.userFirstName = [NSString stringWithFormat:#"%#",[obj valueForKey:#"first_name"]];
}
but in this case loop run many of time and assign null value to variables.
after this I want to parse "LookingData" array but I got null value using this code:
NSDictionary *dictUserLooking=[responseDict valueForKey:#"LookingData"];
What you have (assuming the missing outer []) is a JSON array containing elements that are either arrays or "objects" (dictionaries). The "Profile" data is the contained in the first element of the outer-most array, in this fashion:
outermost array -> single element array -> single element dictionary -> dictionary element for "Profile" -> dictionary containing "Profile" values.
You need to "peel the onion", one layer at a time, to access these values.

Problems with parsing JSON feed in app

The following JSON feed contains orders.
How can I retrieve each order, when it doesn't contain a key (can´t use objectForKey)? Between the opening bracket and the first curly bracket there is no key.
[ <-----
{ <-----
"person": {
"address": "My road",
"city": "My City",
"name": "My Name",
},
"orderDate": "30.05.2012 10:27",
"orderId": 10001,
"orderlines": [
{
"unit": {
"unitId": "RA005",
"name": "My Unit name",
},
"id": 10007,
"deliveryInfo": {
"count": 1,
"date": "30.05.2012",
"format": "MY_FORMAT",
},
"sum": 0,
"details": "Testing",
"priority": 3,
}
],
"received": true,
"status": "REGISTERED",
"sumPrice": 0
},
{
"person": {
"address": "My road 2",
"city": "My City 2",
"name": "My Name 2",
},
"orderDate": "30.04.2012 10:27",
"orderId": 10002,
"orderlines": [
{
"unit": {
"unitId": "RA006",
"name": "My Unit name 2",
},
"id": 10008,
"deliveryInfo": {
"count": 2,
"date": "01.06.2012",
"format": "MY_FORMAT",
},
"sum": 0,
"details": "Testing",
"priority": 2,
}
],
"received": true,
"status": "REGISTERED",
"sumPrice": 0
}
]
whenever you see [] (square brackets), it represents array. so use object at index to return the at indexes. one approach is to pass the object into array like
NSMutableArray *arr = (NSMutableArray*) jsonData;
since the root of your json is an array,
NSError *e = nil;
NSArray *jsonArray = [NSJSONSerialization JSONObjectWithData:data options: NSJSONReadingMutableContainers error: &e];
if (!jsonArray) {
NSLog(#"Error parsing JSON: %#", e);
} else {
for(NSDictionary *item in jsonArray) {
NSLog(#"Item: %#", item);
}
}