LoveTW
LoveTW

Reputation: 3832

JSON naming convention in different object

I know the following two json string are valid, but which one may be better? I think the second one can display more information when I get the field name, however, I am afraid that if I follow these naming rule, the field name might be very long. I hope someone who had considered these designs could give me some suggestions, many thanks!

Case1:

{
  "applicant": {
    "name": "John",
    "age": 30
  },
  "insured": {
    "name": "Marry",
    "age": 25
  }
}

Case2:

{
  "applicant": {
    "applicantName": "John",
    "applicantAge": 30
  },
  "insured": {
    "insuredName": "Marry",
    "insuredAge": 25
  }
}

Upvotes: 2

Views: 805

Answers (1)

jeremija
jeremija

Reputation: 2528

Using the longer notation:

  • is redundant
  • makes the codebase more verbose which can make you lose more time on typing and can sometimes make it harder to read
  • makes it harder to reuse the same objects as you would need to constantly remap properties (i.e. if you wanted to have the same applicant and insured, you would need to remap applicantName to insuredName and applicantAge to insuredAge, along with other properties you might have).
  • makes it harder to reuse any existing code which was made to manipulate an instance of Applicant or Insured because even though the field names may have the same meanings, they are not named the same.

I would prefer the shorter notation and would remap the properties to the longer one only when I would need a flattened object which can sometimes be useful in some MVC/MVVM frameworks such as KnockoutJS. For example, I would use:

{
  "applicant": {
    "name": "John",
    "age": 30
  },
  "insured": {
    "name": "Marry",
    "age": 25
  }
}

and would remap to:

{
  "applicantName": "John",
  "applicantAge": 30,
  "insuredName": "Marry",
  "insuredAge": 25
}

only when I would need it.

Having said that, I would also try to keep the variable names in my code easy to understand - I would always name my array of applicants applicants or applicantsList and not data or items so everybody (including myself) who reads my code always knows what's it about.

Upvotes: 1

Related Questions