Reading a JSON string - iphone

I have a JSON String, in the format;
{
"name": "Alex",
"age": "12"
}
I know how to extract values from the above JSON. but at times, when there are no records in the database. i get a null value printed. (i undestand that this is not a valid JSON)
This null gets caught in the following if-condition.
SBJsonParser *parser = [SBJsonParser new];
NSDictionary *content = [pobjectWithString:[request responseString]];
if(!content){
NSLog(#" when its null it comes to this block");
return;
}
I need to read this value null and save it in a NSString. How can i do this ?
note: i have made use of ASIHTTPRequest to write the above code.

It's not clear what you're asking for. I think you want to detect when a null occurs (which you already seem to do with if(!content) ), then you want to create a string that either is empty, or has the word "null" in it. Why not:
if(!content) {
return #"null";
}
Of course, you could return whatever you wanted in the string.

Related

ParseSwift ParseObject QueryConstraint

I have two collections in a mongo DB.
Here is how a document looks in the first collection (MainCollection):
_id
:"mzWqPEDYRU"
TITLE
:"ZAZ: I want."
ownerID
:"lGutCBY52g"
accessKey
:"0kAd4TOmoK0"
_created_at
:2020-03-13T11:42:11.169+00:00
_updated_at
:2020-03-13T17:08:15.090+00:00
downloadCount
:2
And here is how it looks in the second collection (SecondCollection):
_id
:"07BOGA8bHG"
_p_unit
:"MainCollection$mzWqPEDYRU"
SENTENCE
:"I love nature peace and freedom."
Order
:5
ownerID
:"lGutCBY52g"
AUDIO
:"07067b5589d1edd1d907e96c1daf6da1_VOICE.bin"
_created_at
:2020-03-13T11:42:17.483+00:00
_updated_at
:2020-03-13T11:42:19.336+00:00
There is a parent children relationship between the first and the second collection. In the last document we can see the _p_unit field where the "mzWqPEDYRU" part points to the id of the parent in the first collection.
I have one problem from start with the following code:
func theFunction() {
do {MainCollection.query().find() {
result in
switch result {
case .success(let items):
print("items.count = \(items.count)")
for item in items {
/// ....
}
case .failure(let error):
print("Error in \(#function): \(error)")
}
}
}
}
The way this above code is written works fine and I get the number of elements in MainCollection as one would expect. But then comes a less expected behaviour, in this same code if I replace MainCollection by SecondCollection, instead of getting the number of elements in SecondCollection as I would think. I get an error like:
ParseError(code: ParseSwift.ParseError.Code.unknownError,
message: "Error decoding parse-server response:
Optional(<NSHTTPURLResponse: 0x2837211a0> { URL:}
{ Status Code: 200, Headers {} }) with error:
The data couldn’t be read because it isn’t in the correct format.
Format: Optional(\"{\\\"results\\\": .......
Can anybody point out what is causing this?
It is something like:
var SecondCollection.query(unit == documentOne).find()
The .query() method works in a key/value scheme so it should pass the key as a string and the value as the referenced type, so passing "unit" between double quotes is correct:
do {SecondCollection.query("unit" == cell).find() {
The error you're getting is because cell is a Parse.Object and it is expecting a value in that place (a property in this case).
Please try the following and see if it works for you:
do {SecondCollection.query("unit" == cell.id).find() {

Sequelize returns wrong format from JSONB field

My "Item" model has a JSONB column named "formula".
I want to get it either as Object or JSON string. But what it returns is a string without quoted keys that can't be parsed as JSON.
My code:
async function itemsRead (where) {
const items = await models.item.findAll({
where
})
console.log(items)
return items
}
And what I see and get is:
[
item {
dataValues: {
id: 123,
formula: '{a:-0.81, x:5.12}',
}
},
.
.
.
]
My mistake was in insert (create) phase. I had to pass the original formula object (and not JSON stringified or other string forms) to create()
let formula = {a:-0.81, x:5.12}
models.item.create({id:123, formula})

Comparing two objects in Joi validation (eg. to avoid duplicates)

I'm using Joi to validate a complex form entry. The form asks for two addresses, mainContactAddress and seniorContactAddress. I want to validate them to ensure they aren't the same address.
Each address is an object like this:
{
"line1": "123 Some Street",
"line2": "Some Town",
"county": "Some County",
"postcode": "123 ABC",
"townCity": "City"
}
I initially tried this:
Joi.ukAddress().invalid(Joi.ref('seniorContactAddress'))
(ukAddress() is a custom extension I've created which specifies each of the above fields as a required string.)
This doesn't work, because the equality === comparison between the two objects returns false even when they have the same string values.
I can't see a Joi method to do this. I was hoping to be able to serialise the object (eg. something like Object.values(mainContactAddress).join(',') and then compare the resulting strings) but Joi.ref() only gives, well, a reference to the object, so I can't call functions against it directly.
Any thoughts on how I could achieve this validation/comparison?
I ended up writing a custom rule for my extension:
{
// Enforce a unique address compared to the senior contact
name: 'mainContact',
validate(params, value, state, options) {
// Format addresses into a comparable string,
// making sure we sort them as the stored version
// is in a different order to the form-submitted one.
const serialize = address =>
Object.values(address)
.sort()
.join(',');
const seniorContactAddress = get(
state.parent,
'seniorContactAddress',
[]
);
if (serialize(seniorContactAddress) === serialize(value)) {
return this.createError(
'address.matchesSenior',
{ v: value },
state,
options
);
} else {
return value;
}
}
}
This does feel like an anti-pattern (eg. abusing state to look at other values in the Joi object) but it does what I needed.

Firebase Database REST get with orderBy value and parameters

database.rules.json
{
"rules": {
"meetings" : {
".read": true,
".write": true,
".indexOn" : ["date"]
}
}
}
Request URL
"https://{baseURL}/meetings.json?orderBy=date&equalTo=20181005"
Error Message
error: "orderBy must be a valid JSON encoded path"
But
"https://{baseURL}/meetings.json"
No Error.
What did I do wrong? Plz help me.
The value of the name parameter in your URL needs to be enclosed in " quotes. So:
https://{baseURL}/meetings.json?orderBy="date"&equalTo=20181005
Depending on the way you store the values of the date property, the value of the equalTo parameter may also need be enclosed in " quotes. If you store date as a string, it needs to be:
https://{baseURL}/meetings.json?orderBy="date"&equalTo="20181005"
For more on this, read the Firebase documentation on querying using the REST API.
I have faced the exact issue.. and the trick is..the passing value should be "string " encode,
as example below..
searchRecordById(recordId: string) {
return this.http.get(
`https://your-app.firebaseio.com/skdocs.json`,
{
params: {
**orderBy: '"folder"',
equalTo: '"Panchla-2"',**
},
}
);
}
You'll need to escape the quotes for it to work. E.g.
"https://{baseURL}/meetings.json?orderBy=\"date\"&equalTo=\"20181005\""
If you are using curl then try this:
curl 'https://{baseURL}/meetings.json?orderBy="date"&equalTo=20181005'
If you fetch url from web or etc then url should be :
https://{baseURL}/meetings.json?orderBy="date"&equalTo=20181005

Parsing JSON: brackets in response

I want to parse this JSON YouTube recently featured.
This is how I get the title of the videos:
NSString *response = [request responseString];
responseDict = [response JSONValue];
videoTitleArray = [responseDict valueForKeyPath:#"feed.entry.title.$t"];
And it works like I want it.
But I also want to display the author of the video.
But the following code for this does not work properly:
videoAuthorArray = [responseDict valueForKeyPath:#"feed.entry.author.name.$t"];
NSLog(#"%#", videoAuthorArray);
The list of the authors I get looks like this:
(
author 1
),
(
author 2
),
(
author 3
),
(
author 4
),
I can't display the names in for example a table view because of the brackets.
How can I display the author names like the video titles?
When you see an Author you see this:
"author":[{"name":{"$t":"mls"},"uri":{"$t":"http://gdata.youtube.com/feeds/api/users/mls"},"yt$userId":{"$t":"SZbXT5TLLW_i-5W8FZpFsg"}}]
this means: author is an array of author objects
each author object has: name object, a uri object and a yt$userId object
each of this objects described above is a NSDictionary
formated we have:
"author":[
{
"name": {
"$t":"mls"
},
"uri": {
"$t":"http://gdata.youtube.com/feeds/api/users/mls"
},
"yt$userId":{
"$t":"SZbXT5TLLW_i-5W8FZpFsg"
}
}
],
so if you have your videoAuthorArray each element is an NSDictionary and has this keys: name, uri and yt$userId
each of this objects has an NSDictionary with a single key: $t witch has the value