0

I thought I know but later on I stuck and became confused. I want to ask is it possible to 'think relationship' in json or it can be done only when u are designing your backend?

noob
  • 101
  • 6

1 Answers1

0

JSON doesn't support object references, but JavaScript objects do. You can even store functions, as they are first class citizens.

http://en.wikipedia.org/wiki/JSON#Object_references

var anna = {name: "Anna"};
var bob = {name: "Bob", knows: [anna]};
var charlie = {name: "Charlie", knows: [anna, bob]}
anna.knows = [charlie, bob];

// 'Bob'
alert(charlie.knows[0].knows[1].name)

// -------------------------------------------------

var call = function(destination) {
    alert(this.name + " calls " + destination.name);
}
bob.call = call;

// 'Bob calls Charlie'
bob.call(charlie);

But beware of infinite loops!
(bob knows anna, anna knows bob, bob knows anna, ...)

In JSON, relationships can only be represented by value (which is ideally the unique ID of a record). You basically duplicate the name, and need to look up the entry with this name to find what it refers to.

var ob_from_json = JSON.parse('
    {
        "bob": {"name": "Bob", "knows": ["anna"]},
        "anna: {"name": "Anna", "knows": ["bob"]}
    }
');

// 'Anna'
ob_from_json[ob_from_json["bob"].knows[0]].name
CodeManX
  • 11,159
  • 5
  • 49
  • 70
  • what if I want to separate user and their friends as 2 seperated table? I know how to access data of json. – noob Apr 14 '14 at 13:06
  • You seem to be using a relational database system (MySQL). Relational DBs are actually bad at storing relationships. To create a n:m relationalship, you need an additional table that stores an ID and two foreign keys - the user IDs. If Anna knows Bob and Charlie, add two records to that table (1, "anna", "bob"), (2, "anna", "charlie"). See e.g. http://stackoverflow.com/questions/260441/how-to-create-relationships-in-mysql for more. – CodeManX Apr 14 '14 at 13:12
  • yup I know that. I would like to ask how's the flow to develop app especially Single page app. I saw many ppl prepare their data of json and create the front-end of it. I wonder in their db logic is done in their json, or they design the relationship later on ? – noob Apr 14 '14 at 13:22
  • 1
    I would assume most SPAs don't use relational databases, but document-based DBs like MongoDB or CouchDB. They usually support JSON natively and the document-based design fits very well to the JSON format. A relationship would be established by referencing another document id, but with the benefit of having all relationships of a user to others in a single list, as a document attribute. If you wanna use MySQL, it's worth to read about Object Relational Mappers (ORM). It's much more convenient to use PHP + MySQL with a persistence layer, that manages the data mapping and evaluation. – CodeManX Apr 14 '14 at 15:14