How to remove first and last { } in a NSString in iOS? - ios

I want to remove first and last bracket from my NSString.
{
"Questions" : [
{
"title" : "This is my Question",
"question_id" : "123123123213",
"answers" : [
"correct answer 1",
"wrong answer 1",
"wrong answer 2",
"wrong answer 3"
],
"media_type" : "",
},
{
"title" : "This is my Question",
"question_id" : "2342342342342",
"answers" : [
"correct answer 1",
"wrong answer 1",
"wrong answer 2",
"wrong answer 3"
],
"media_type" : "",
}
]
}
I want to remove only first and last { } from the above NSString.
Make sure its not Dictionary. I have this in NSString.

UPDATE
The option is serializing:
NSData *data = [str dataUsingEncoding:NSUTF8StringEncoding];
NSDictionary *dictJson = [NSJSONSerialization JSONObjectWithData:data
options:kNilOptions
error:nil];
NSArray *arr = dictJson[#"Questions"];
for (NSDictionary *dict in arr)
{
NSLog(#"title ==%#",dict[#"title"]);
.....
}
UPDATE 2
But BE CAREFUL with your string. It's wrong. You have to check the commas after media_type:
{
"Questions" : [
{
"title" : "This is my Question",
"question_id" : "123123123213",
"answers" : [
"correct answer 1",
"wrong answer 1",
"wrong answer 2",
"wrong answer 3"
],
"media_type" : ""**,** //THIS
},
{
"title" : "This is my Question",
"question_id" : "2342342342342",
"answers" : [
"correct answer 1",
"wrong answer 1",
"wrong answer 2",
"wrong answer 3"
],
"media_type" : ""**,** //AND THIS
}
]
}
No commas have to go there.

Related

How to provide custom IDs during JSON import in Firebase Database?

How can I set the ID of the record or doc in the Firebase Database when I use the JSON import functionality?
When I import the file it creates sequential IDs (0, 1, 2 etc), but I would like to specify an ID so its easier to retrieve the record.
Below is my sample JSON data:
[
{
"GameID": 2234567890,
"GameName": "Team 3 vs Team 2",
"GameLocation": "Rink 4 Hockey Town",
"TypeOfGame": "Tournament Round Robin",
"HomeTeam": {
"Name": "Team 1",
"ImageUrl": "My Image URL 1",
"Level": "16AAA",
"Country": "USA"
}
}, {
"GameID": 1234567890,
"GameName": "Team 1 vs Team 2",
"GameLocation": "Rink 1 Hockey Town",
"TypeOfGame": "Tournament Round Robin",
"HomeTeam": {
"Name": "Team 1",
"ImageUrl": "My Image URL 1",
"Level": "16AAA",
"Country": "USA"
}
}
]
There is no way in which you can import a JSON file and generate a custom Id in the same time. You are getting (0, 1, 2 etc) as Ids because there is no unique identifier between those objects and Firebase sees all those records as a list, and therefor provides those ids for you.
To achieve what you want, you need to add that data programmatically using the push() function provided by Firebase for each record. This method generates a unique id which easy to be used in the future.
[ {
"1234567890" : {
"GameID" : 1234567890,
"GameLocation" : "Rink 1 Hockey Town",
"GameName" : "Team 1 vs Team 2",
"HomeTeam" : {
"Country" : "USA",
"ImageUrl" : "My Image URL 1",
"Level" : "16AAA",
"Name" : "Team 1"
},
"TypeOfGame" : "Tournament Round Robin"
},
"2234567890" : {
"GameID" : 2234567890,
"GameLocation" : "Rink 4 Hockey Town",
"GameName" : "Team 3 vs Team 2",
"HomeTeam" : {
"Country" : "USA",
"ImageUrl" : "My Image URL 1",
"Level" : "16AAA",
"Name" : "Team 1"
},
"TypeOfGame" : "Tournament Round Robin"
}
} ]

Querying Child Nodes Based on a Particular Value (Swift 3, Firebase)

I am trying to pass a phone number (Ex. 1111111111) and see if it matches any of the entries in my Firebase Database. I am having problems sorting through the database and looking up the phone number. Below is the Firebase Database's JSON code.
{
"Users" : {
"3SMHwMuA8HQm9yLoivxYoCtUccr1" : {
"Email" : "firstname1.lastname1#gmail.com",
"First Name" : "First Name 1",
"Last Name" : "Last Name 1",
"Phone Number" : "(111) 111-1111"
},
"NvQiGzASw2QDAMcBQLx1HNzR8ZM2" : {
"Email" : "firstname2.lastname2#gmail.com",
"First Name" : "First Name 2",
"Last Name" : "First Name 2",
"Phone Number" : "(222) 222-2222"
},
"RuVMfHUC8qQg8KGVJitEkzq9Tsy2" : {
"Email" : "firstname3.lastname3#gmail.com",
"First Name" : "First Name 3",
"Last Name" : "Last Name 3",
"Phone Number" : "(333) 333-3333"
}
}
}
This is the code that I wrote. It is not giving the correct result.
phoneNumber: Int = 1111111111
ref = Database.database().reference()
let phoneNoInDatabase = ref.child("Users").queryEqual(toValue: phoneNo_pb_int)
let phoneNoInDatabaseInt = Int(phoneNoInDatabase.components(separatedBy: CharacterSet.decimalDigits.inverted).joined())
if phoneNoInDatabase_int == phoneNo_pb_int {
// Success!
print("User Found")
}
else {
// Error!
print("User not Found")
}
You're missing an instruction for what child to filter on:
let phoneNoInDatabase = ref.child("Users").queryOrdered(byChild: "Phone Number").queryEqual(toValue: phoneNo_pb_int)

Adding Implementation Notes and Description to Swagger UI

I am attempting to add Implementation Notes and Description to my Swagger UI. However, neither show up on the UI when implemented as below:
{
"swagger" : "2.0",
"info" : {
"description" : "The definition of the Rest API to service plugin over https on port 9443.",
"version" : "1.0",
"title" : "Plugin Rest API",
"contact" : {
"name" : "John Doe",
"email" : "john.doe#gmail.com"
}
},
"basePath" : "/service",
"tags" : [ {
"name" : "service"
} ],
"schemes" : [ "https" ],
"paths" : {
"/entry" : {
"get" : {
"notes" : "This is a note",
"method" : "get",
"tags" : [ "service" ],
"summary" : "Get an entry by first name and last name",
"description" : "This is a description",
"operationId" : "getEntry",
"produces" : [ "application/xml", "application/json" ],
"parameters" : [ {
"name" : "first",
"in" : "query",
"description" : "The first name",
"required" : true,
"type" : "string"
}, {
"name" : "last",
"in" : "query",
"description" : "The last name",
"required" : true,
"type" : "string"
} ],
"responses" : {
"200" : {
"description" : "Matching entry, or entries, if any, were returned",
"schema" : {
"$ref" : "#/definitions/Service"
}
}
}
},
I am not sure what I am doing wrong in my code. I've tested it on various sample swagger.json files and I cannot seem to get it to work.
notes is not a swagger field. See the documentation
Your description field is written twice, so the first one has been overridden.
you can add implementation notes using notes tag in #ApiOperation annotation as shown below,
#ApiOperation(notes = "Your Implementation Notes will show here[![enter image description here][1]][1]", value = "Add Customer Payment Details and Generate Payment Link through Batch.", nickname = "insertPaymentBatch", tags =
"Insert Payment" )

How to aggregate this data more efficiently?

I am using Rail 3 with Mongoid as my ODM.
I have imported the following documents into MongoDB:
{ "make" : "Make A", "model": "Model 1", "variant" : "Variant 1" }
{ "make" : "Make B", "model": "Model 3", "variant" : "Variant 1" }
{ "make" : "Make A", "model": "Model 2", "variant" : "Variant 2" }
{ "make" : "Make A", "model": "Model 2", "variant" : "Variant 1" }
The following code produces a nested hash of sorted distinct values:
#makes = Item.all.distinct(:make).sort
#models = {}
#makes.each do |make|
#models[make] = Item.where(:make => make).distinct(:model).sort
end
#output = {}
#models.each_pair do |make, models|
#output[make] = {}
models.each do |model|
#output[make][model] = Item.where(:make => make, :model => model).distinct(:variant).sort
end
end
The resulting hash looks like this:
{
"Make A" => {
"Model 1" => ["Variant 1"],
"Model 2" => ["Variant 1", "Variant 2"]
},
"Make B" => {
"Model 3" => ["Variant 1"]
}
}
This all works fine, but is very inefficient as it involves so many queries. Is there a better way of achieving this, perhaps by having MongoDB perform the aggregation?
I solved this using MongoDB's MapReduce function with the following paramaters:
map = function() {
emit( 1, { make: this.make, model: this.model, variant: this.variant } );
}
reduce = function(key, values) {
var result = {};
values.forEach(function(value) {
if (!result[value.make]) result[value.make] = {};
if (!result[value.make][value.model]) result[value.make][value.model] = [];
result[value.make][value.model].push(value.variant);
});
return result;
}
This returns a single MongoDB result in the same format as the Ruby hash above.

MongoDB/Mongoid: Can one query for ObjectID in embedded documents?

For the record, I'm a bit of a newbie when it comes to Rails and MongoDB.
I'm using Rails+Mongoid+MongoDB to build an app and I've noticed that Mongoid adds ObjectID to embedded documents for some reason.
Is there any way to query all documents in a collection by ObjectID both the main documents and nested ones?
If I run this command
db.programs.findOne( { _id: ObjectId( "4d1a035cfa87b171e9000002" ) } )
I get these results which is normal since I'm querying for the ObjectID at root level.
{
"_id" : ObjectId("4d1a035cfa87b171e9000002"),
"created_at" : "Tue Dec 28 2010 00:00:00 GMT+0000 (GMT)",
"name" : "program",
"routines" : [
{
"name" : "Day 1",
"_id" : ObjectId("4d1a7689fa87b17f50000020")
},
{
"name" : "Day 2",
"_id" : ObjectId("4d1a7695fa87b17f50000022")
},
{
"name" : "Day 3",
"_id" : ObjectId("4d1a76acfa87b17f50000024")
},
{
"name" : "Day 4",
"_id" : ObjectId("4d1a76ecfa87b17f50000026")
},
{
"name" : "Day 5",
"_id" : ObjectId("4d1a7708fa87b17f50000028")
},
{
"name" : "Day 6",
"_id" : ObjectId("4d1a7713fa87b17f5000002a")
},
{
"name" : "Day 7",
"_id" : ObjectId("4d1a7721fa87b17f5000002c")
}
],
"user_id" : ObjectId("4d190cdbfa87b15c2900000a")
}
Now if I try to query with an ObjectID with one of the embedded document (routines) I get null like so.
db.programs.findOne( { _id: ObjectId( "4d1a7689fa87b17f50000020" ) } )
null
I know one can query embedded objects like so
db.postings.find( { "author.name" : "joe" } );
but that seems a bit redundant if you get passed an ObjectID of some sort and want to find in what document that ObjectID resides.
So I guess my question is this...
Is it possible, with some method I'm not familiar with, to query by ObjectID and search the ObjectID's in the embedded documents?
Thanks.
You can't query ObjectIDs globally like that. You would have to do
db.programs.find({"routines._id": ObjectId("4d1a7689fa87b17f50000020")})
no, you can search only by field like { "routines._id" : ObjectId("4d1a7689fa87b17f50000020")}
If you want to get the matched sub-document only you can use $elemMatch with '$' operator like below:
db.programs.find({"_id" : ObjectId("4d1a035cfa87b171e9000002"),
routines:{$elemMatch:{"_id" : ObjectId("4d1a7689fa87b17f50000020")}}},{"routines.$":1})
It will return you only that matched sub-document instead of the complete sub-document.

Resources