JSON-Framework Parsing data in a strange order - iphone

I currently have an ordered JSON string being passed into my iPhone app, which is then being parsed using the JSON Framework.
The data is as follows:
"league_table": object{
"Premiership": array[6],
"Championship": array[6],
"Division 1": array[6],
"Division 2": array[6],
"Division 3": array[6]
}
However when it parses that, it throws out a weird order.
Division 2
Division 1
Championship
"Division 3"
Premiership
Which I got by calling : NSLog(#"%#",[dictionaryValue allKeys]);.
Has anyone experienced this before? Any idea what to do to sort it again?
UPDATE ::
The shortened UN-Parsed JSON is here :
{"league_table":
{
"Premiership":[],
"Championship":[],
"Division 1":[],
"Division 2":[],
"Division 3":[]}
}
As far as I can tell, this is a Key/Value Pair, so it should be parsed in the same order.
For instance going to http://json.parser.online.fr/ and pasting that in will parse it in the correct order.
However the JSON-Framework doesn't parse it the same, it parses it in a strange order with no real sorting going on

JSON object fields don't have a defined order. If you want key/value pairs in a defined order, there are basically two options:
An array of single-field objects:
[{"Premiership": array[6]},
{"Championship": array[6]},
{"Division 1": array[6]},
{"Division 2": array[6]},
{"Division 3": array[6]}]
An array of key/value pairs:
[["Premiership", array[6]],
["Championship", array[6]],
["Division 1", array[6]],
["Division 2", array[6]],
["Division 3", array[6]]]
Sidenote: I'm half-guessing that the relationship between the sample data and JSON. I don't know what object and array[6] are doing there.

Yep, I've seen that before.
Does this cause you a problem? it looks like a Dictionary (keyed) .. so I guess your application just accesses the required elements by it's key.
I believe a JSON array format would maintain the order.
EDIT
Ok, so you need to maintain the order ... but from what you say, it looks like the key isn't important.
Are you in control of the creation of the JSON string ? If so, could you present the data like this :
[
{
"leagueName":"Premiership",
"leagueLines":[...]
},
{
"leagueName":"Championship",
"leagueLines":[...]
},
{
"leagueName":"League One",
"leagueLines":[]
},
... etc ....
]
I've put in the leagueName in just for information ... who know's you might need it for something :)
Good Luck

Related

Is this JSON oddball ? - SwiftyJSON

I got the unusual json (actually from IBM Bluemix), shown below,
Thank goodness, trusty and heartwarming SwiftyJSON was able to get the values, like this...
let mauves = json["blue"][0]["brown"][0]["mauve"]
However, notice there are weird sort of "empty unnamed array nested things" in the JSON (hence the [0] calls to Swifty).
My question, in short,
is this valid json?
Even if valid, is it "crappy"? Or am I wrong, it's totally idiomatic? (Maybe I've just been dating the wrong services for decades, I don't know.)
I appreciate that running it through online validators seems to say "valid" (except this one http://json.parser.online.fr gives red things), but, you know, who trusts online services? Ask experts on SO....)
--
{
"red" : 1,
"green" : 4,
"blue" : [
{
"yellow" : "word",
"brown" : [
{
"orange" : "1826662593",
"gold" : "23123",
"mauve" : [
{
"a" : "Beagle",
"b" : 0.979831
},
{
"a" : "Chow",
"b" : 0.937588
},
{
"a" : "Hound",
"b" : 0.987798
}
]
}
]
}
]
}
--
The JSON is valid. The blue member contains an array with 1 element (at index [0] which is the yellow object, and this is repeated for orange.
When I paste it into json.parser.online.fr it reports it as valid for me - are you accidentally including other text around it?
The JSON is perfectly valid - your validators are not lying to you. I don't know if this JSON contains real keys, or if the names have been changed to protect the innocent (it certainly looks like nonsense), but in a real world situation there are frequently arrays that contain one element (because they might contain zero or many elements!).

MongoDB - Document with different type of value

I'm very new to MongoDB, i tell you sorry for this question but i have a problem to understand how to create a document that can contain a value with different "type:
My document can contain data like this:
// Example ONE
{
"customer" : "aCustomer",
"type": "TYPE_ONE",
"value": "Value here"
}
// Example TWO
{
"customer": "aCustomer",
"type": "TYPE_TWO",
"value": {
"parameter1": "value for parameter one",
"parameter2": "value for parameter two"
}
}
// Example THREE
{
"customer": "aCustomer",
"type": "TYPE_THREE",
"value": {
"anotherParameter": "another value",
{
"someParameter": "value for some parameter",
...
}
}
}
Customer field will be even present, the type can be different (TYPE_ONE, TYPE_TWO and so on), based on the TYPE the value can be a string, an object, an array etc.
Looking this example, i should create three kind of collections (one for type) or the same collection (for example, a collection named "measurements") can contain differend kind of value on the field "value" ?
Trying some insert in my DB instance i dont get any error (i'm able to insert object, string and array on property value), but i would like to know if is the correct way...
I come from RDBMS, i'm a bit confused right now.. thanks a lot for your support.
You can find the answer here https://docs.mongodb.com/drivers/use-cases/product-catalog
MongoDB's dynamic schema means that each need not conform to the same schema.

Mongo DB and Go - using dynamic data models

I am faced with a problem where I am not sure which path to take. So I am asking it here. I have an application where there can be products and there can be metadata for a product. These metadata can be created and deleted from the front end. So let's say, today a each product has two meta data (e.g. Name, Price) then tomorrow it can be three, four or more or even less than two. So this is dynamic. I am trying to represent the data as follows
Product =
{
"_id": mongo
"Name": string
"Description": string
"BasePrice": number
"CreatedBy": user mongo _id
"CreatedAt": timestamp
"ModifiedAt": timestamp
"MetaData": BSON object (having all the keys from ProductMetadata collection and their values. e.g. {"Category": "table ware", "Material": "oak wood, copper", "Length": 5.6})
}
ProductMetadata =
{
"_id": mongo
"Name": string (e.g. - "Category" or "Material" or "Height")
"Type": string (indicating what kind of value it can hold like string/integer/array. e.g. - "string")
"CreatedAt": timestamp
"ModifiedAt": timestamp
}
As you can see this is a pure dynamic situation so having a structure at the code level which represent the model is impossible.
My problem is, how do I implement such a thing using mgo and Go lang? If I need to use reflection then can some one please point me towards a good blog/tutorial where I can get a little bit more info. Or if you think that there is a fundamental problem in the approach of modeling the data then please correct me so that it can be easily implemented using Go.
In Python, it would not be a problem to implement this. I know that. But I am confused about the Go implementation.
Please help.
Thanks in advance
If Keys for metadata are unique, why not just use a map.
meaning your Product struct looks like:
struct Product {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Description string
... omitted other fields ...
MetaData map[string]map[string]interface{} // map of string -> map of string -> anything
}
If you can have more than one instance of a given meta data, ie: 2 categories, use a list:
struct Product {
ID bson.ObjectId `bson:"_id,omitempty"`
Name string
Description string
... omitted other fields ...
MetaData []map[string]interface{} // list of maps of string -> anything
}

MongoDB: Find document given field values in an object with an unknown key

I'm making a database on theses/arguments. They are related to other arguments, which I've placed in an object with a dynamic key, which is completely random.
{
_id : "aeokejXMwGKvWzF5L",
text : "test",
relations : {
cF6iKAkDJg5eQGsgb : {
type : "interpretation",
originId : "uFEjssN2RgcrgiTjh",
ratings: [...]
}
}
}
Can I find this document if I only know what the value of type is? That is I want to do something like this:
db.theses.find({relations['anything']: { type: "interpretation"}}})
This could've been done easily with the positional operator, if relations had been an array. But then I cannot make changes to the objects in ratings, as mongo doesn't support those updates. I'm asking here to see if I can keep from having to change the database structure.
Though you seem to have approached this structure due to a problem with updates in using nested arrays, you really have only caused another problem by doing something else which is not really supported, and that is that there is no "wildcard" concept for searching unspecified keys using the standard query operators that are optimal.
The only way you can really search for such data is by using JavaScript code on the server to traverse the keys using $where. This is clearly not a really good idea as it requires brute force evaluation rather than using useful things like an index, but it can be approached as follows:
db.theses.find(function() {
var relations = this.relations;
return Object.keys(relations).some(function(rel) {
return relations[rel].type == "interpretation";
});
))
While this will return those objects from the collection that contain the required nested value, it must inspect each object in the collection in order to do the evaluation. This is why such evaluation should really only be used when paired with something that can directly use an index instead as a hard value from the object in the collection.
Still the better solution is to consider remodelling the data to take advantage of indexes in search. Where it is neccessary to update the "ratings" information, then basically "flatten" the structure to consider each "rating" element as the only array data instead:
{
"_id": "aeokejXMwGKvWzF5L",
"text": "test",
"relationsRatings": [
{
"relationId": "cF6iKAkDJg5eQGsgb",
"type": "interpretation",
"originId": "uFEjssN2RgcrgiTjh",
"ratingId": 1,
"ratingScore": 5
},
{
"relationId": "cF6iKAkDJg5eQGsgb",
"type": "interpretation",
"originId": "uFEjssN2RgcrgiTjh",
"ratingId": 2,
"ratingScore": 6
}
]
}
Now searching is of course quite simple:
db.theses.find({ "relationsRatings.type": "interpretation" })
And of course the positional $ operator can now be used with the flatter structure:
db.theses.update(
{ "relationsRatings.ratingId": 1 },
{ "$set": { "relationsRatings.$.ratingScore": 7 } }
)
Of course this means duplication of the "related" data for each "ratings" value, but this is generally the cost of being to update by matched position as this is all that is supported with a single level of array nesting only.
So you can force the logic to match with the way you have it structured, but it is not a great idea to do so and will lead to performance problems. If however your main need here is to update the "ratings" information rather than just append to the inner list, then a flatter structure will be of greater benefit and of course be a lot faster to search.

Searching an attribute in referenced documents with Meteor

I have a relationship, like this.
{
_id : 1,
"data" : "value"
}
{
_id: 2,
"otherData" : "Other value",
"mainData: 1
}
As you can se, I have two documents and the second one has a reference to the first one.
It's any way to make a search like this??
Collection.find({"mainData.data" : "value"});
Thanks for your help.
With any coding you have to keep track of what you're doing.
Collection.find({"mainData.data" : "value"});
Both of those keys are undefined in your code and so Collection.find can't return anything. Also, your mainData key doesn't have a key called data so no matter what that will return undefined.
So what you would do is write something to get the mainData reference stored as a string.
let referenceCollection = Collection.find({'_id' : 2}); // 2 should really be a string
let referenceKey = referenceCollection.mainData; // this will return 1
Collection.find({'_id': referenceKey})
You could do a lot to make that better, but hopefully you see that your relationship only works when there's actual data to look for.