JSON Naming Convention (snake_case, camelCase or PascalCase) [closed]
Asked Answered
C

7

645

Is there a standard on JSON naming?
I see most examples using all lower case separated by underscore, aka snake_case, but can it be used PascalCase or camelCase as well?

Carnallite answered 4/4, 2011 at 19:43 Comment(11)
I was curious what some industry leaders chose. Twitter and Facebook API's use snake_case while Microsoft and Google use camelCase.Moshemoshell
@Moshemoshell that is because Twitter is using Ruby and Facebook is using PHP. Ruby and PHP are into snake_case. Microsoft and Google are well using C/.NET and Java respectively. Oh that's right .Net and Java are into camelCase maybe. It's all about the conventions of the programming languagesNathanaelnathanial
There is no standard, but the convention seems to be to use the standard of the technology of the receiving system.Gosling
All are correct there is no stringent convention for names/keys in JSON. Though, I highly recommend to avoid kebab-case as it cannot be accessed by dot(.) notation in javascript and has to be accessed using array[] notation which I think is tedious.Protectionist
If you are sending JSON from a web browser, it might make sense to use kebab-case. This is because the data will likely be coming from an HTML form, and each key will be derived from the name of the form element, which will be a CSS name, which uses kebab-case by convention.Misbeliever
From my experience for JSON snake_case is more appropriate. 1. Using camel case you lose the casing in many databases or may need special handling. For instance, Cassandra CQL is case-insensitive. If you were to map this JSON to DB records, makes sense to use snake_sase. 2. Hyphen is considered a special char in many languages and not accepted in names.Garrott
Zalando declares some rules: opensource.zalando.com/restful-api-guidelines/#130, opensource.zalando.com/restful-api-guidelines/#118, so if you generally follow these Zalando rules it might be clear for youMacao
There's nothing opinion based about convention and standard or best practice. Experienced professionals will be aware of a variety of conventions which are key to usability and maintainability for a particular system, and may even be documented tantamount to actual standards, or literally be a standard as in the case of Python PEPs for instance. There are also often practical considerations with different conventions which can be discussed in order to determine the best fit for a particular project. This question is NOT OPINION BASED.Minoan
It's possibly significant that questions on payload naming conventions never seem to get out of the starting box of which case to use. SO may contribute to this sad state of affairs by paying the admins to close questions as opinion based. One day, in an enlightened future, we may find enough space to start discussion the actual names and types in our payloads as well, mentioning such problems as the boolean trap and other common naming and typing problems.Minoan
@Minoan There is no standard, and that means this is the definition of opinion-based. And in case you didn't know it yet, there is no such thing as best practices, or best practices are at best someones opinion or description of something that works in a specific context, which might not apply to your case.Datcha
Which standard says practice without a standard is worthless? Before a standard is wrtiten there must be practice to establish what the standard codifies. Almost every answer on SO is opinion based. Juniors and new comers can get a great deal of uncontentious answers from logical explanations of practice that wouldn't occur to them (until they've accumulated some experience like those that answer the questions). The mere fact that no-one else wrote it down yet is the main reason why they ask it on SO. The practices are always described with context so the application is clear. Think again.Minoan
P
353

There is no SINGLE standard, but I have seen 3 styles you mention ("Pascal/Microsoft", "Java" (camelCase) and "C" (underscores, snake_case)) -- as well as at least one more, kebab-case like longer-name).

It mostly seems to depend on what background developers of the service in question had; those with c/c++ background (or languages that adopt similar naming, which includes many scripting languages, ruby etc) often choose underscore variant; and rest similarly (Java vs .NET). Jackson library that was mentioned, for example, assumes Java bean naming convention (camelCase)

UPDATE: my definition of "standard" is a SINGLE convention. So while one could claim "yes, there are many standards", to me there are multiple Naming Conventions, none of which is "The" standard overall. One of them could be considered the standard for specific platform, but given that JSON is used for interoperability between platforms that may or may not make much sense.

Perambulator answered 9/6, 2011 at 16:53 Comment(8)
Sticking with the background of the devs is important, but JSON sticks with the Javascript standard. Your first statement isn't quite correct. But definately stick with the naming conventions of your team.Walcoff
It would be interesting to see some statistics, as there is constant friction between people who claim connection between JSON and Javascript (beyond just historical heritage), and those who think there is little currently that connects JSON to Javascript. I belong to the latter camp. But I would be interested in knowing relative usage patterns.Perambulator
@Perambulator C# uses PascalCase in the majority of cases, not camelCase.Yockey
@Yockey yes. What is your point? (also, pascal-case sometimes called "upper camel case")Perambulator
@Perambulator would you consider updating your answer to include mention of Googles Style GuideHoagy
Can I use all caps like eg: "ROLLNO": 12345?Microchemistry
@mannedear nothing in JSON spec prevents that so sure. It could be considered yet another naming convention. :)Perambulator
JSON case conventions like camelCase, snake_case, and their variations pose no issues for deserialization in ECMAscript-type languages (Java, C#, JavaScript). While camelCase and snake_case convert seamlessly to object properties, kebab-case might challenge applications with limited deserialization control, e.g. only a subset of Java or C# is allowed. It's better suited for map or dictionary keys than direct object properties. Consider the consuming app's deserialization capabilities when choosing case conventions; snake_case and camelCase are generally friendlier options.Examen
S
611

In this document Google JSON Style Guide (recommendations for building JSON APIs at Google),

It recommends that:

  1. Property names must be camelCased, ASCII strings.

  2. The first character must be a letter, an underscore (_), or a dollar sign ($).

Example:

{
  "thisPropertyIsAnIdentifier": "identifier value"
}

My team consistently follows this convention when building REST APIs. There are some reasons:

  • First, the JSON convention should be independent of the programming languages because we want our APIs to be consistent doesn't matter whether there are some APIs implemented using a camelCase language (e.g. Java), some others using snake_case language (e.g. Python).
  • Also, most of our clients are webapp so camelCase is preferred
  • If the client prefers snake_case, it still can easily convert data between snake_case and camelCase (with the help of libraries)

But I agree that if all the applications use the same type of language (e.g. snake_case), the JSON convention should also follow.

Shotton answered 10/10, 2013 at 4:58 Comment(8)
Can someone explain why and when you would use an underscore to prefix a property name? A reference would be useful, not just an opinion.Accouterment
@SeanGlover, when creating Javascript "classes", some people people start "private" methods/properties with an underscore. I find in inheritance scenarios, it's much simpler to delineate an instance method as private by using an "_" rather than using a complex system of extending prototypes with closures to mimic classical inheritance's private instance method behavior.Shagbark
@Grant Your example is not in camel Case right? { "ThisPropertyIsAnIdentifier": "identifier value" }Pointillism
@MaduraPradeep ProperCase is also camel case, sometimes called UpperCamelCase. en.wikipedia.org/wiki/Camel_caseLusty
citing Google is not a propper answer. they just support a certain convention/guideline and it looks to be java making sense as they are pretty java oriented.Damascene
Also a hot topic here github.com/json-api/json-api/pull/1247Hoagy
This does not answer the question. This is just one of many style guides, and there are many other style guides mandating either snake_case, PascalCase and camelCase. Citing your own team's preference is irrelevant. Abel's answer below is a much better answer to the question.Tindall
this answer is specific to what Google uses and not recommended by any standard.Cule
N
433

ECMA-404

The JSON syntax does not impose any restrictions on the strings used as names,...

There is no standard naming of keys in JSON and that camelCase or snake_case should work fine.

TL;DR

Here is a rule-of-a-thumb which I think most of the developers use.

Technology stack Naming convention Reason/guide
Python » JSON » Python snake_case Unanimous
Python » JSON » PHP snake_case Unanimous
Python » JSON » Java snake_case or camelCase Lean on where the business logic resides. Take advantage of the extrinsic style of Java.
Python » JSON » back‑end JavaScript snake_case or camelCase Lean on where the business logic resides.
Python » JSON » front‑end JavaScript snake_case Screw the front-end anyway
Python » JSON » you do not know snake_case Screw the parser anyway
PHP » JSON » Python snake_case Unanimous
PHP » JSON » PHP snake_case Unanimous
PHP » JSON » Java snake_case or camelCase Lean on where the business logic resides. Take advantage of the extrinsic style of Java.
PHP » JSON » back‑end JavaScript snake_case or camelCase Lean on where the business logic resides.
PHP » JSON » front‑end JavaScript snake_case Screw the front-end anyway
PHP » JSON » you do not know snake_case Screw the parser anyway
Java » JSON » Python camelCase or snake_case Lean on where the business logic resides. Take advantage of the extrinsic style of Java.
Java » JSON » PHP camelCase or snake_case Lean on where the business logic resides. Take advantage of the extrinsic style of Java.
Java » JSON » Java camelCase Unanimous
Java » JSON » JavaScript camelCase Unanimous
Java » JSON » you do not know camelCase Screw the parser anyway
back‑end JavaScript » JSON » Python camelCase or snake_case Lean on where the business logic resides.
front‑end JavaScript » JSON » Python snake_case Screw the front-end anyway
back‑end JavaScript » JSON » PHP camelCase or snake_case Lean on where the business logic resides.
front‑end JavaScript » JSON » PHP snake_case Screw the front-end anyway
JavaScript » JSON » Java camelCase Unanimous
JavaScript » JSON » JavaScript camelCase Original
JavaScript » JSON » you do not know camelCase Screw the parser anyway

Driving factors

Imposing a naming convention is very confusing because JSON alone does not impose a standard. However, this can easily be figured out if you break it down into components.

JSON generator

Programming language Naming convention
Python snake_case
PHP snake_case
Java camelCase
JavaScript camelCase

JSON parser

Programming language Naming convention
Python snake_case
PHP snake_case
Java camelCase
JavaScript camelCase

Bulk of business logic

You have to decide which side has the heavier business logic, is it the JSON generator side or the JSON parser side?

Natural belongingness

Programming language Natural belongingness
Python intrinsic
PHP intrinsic
Java extrinsic
JavaScript intrinsic

Intrinsic - Programming language where JSON is accessed naturally similar to accessing native objects and arrays.

Extrinsic - Programming language where JSON is accessed differently than accessing native objects and arrays. Below is an example of Java's com.google.gson package:

/**
 * Using a method to access a property instead of using the standard 'dot.syntax'
 */
JsonElement.getAsString("snake_cased_key");

Some actual implementations

Conclusions

Choosing the right JSON naming convention for your JSON implementation depends on your technology stack. There are cases where you can use snake_case, camelCase, or any other naming convention.

Another thing to consider is the weight to be put on the JSON-generator vs the JSON-parser and/or the front-end JavaScript. In general, more weight should be put on business logic side.

Also, if the JSON-parser side is unknown then you can declare what ever can work for you.

Nathanaelnathanial answered 18/8, 2014 at 17:29 Comment(20)
"Person":isn't camelCase :)Brannan
@Brannan that's probably because they also followed the convention of schema.org. Starting the key with a capital letter means that it is a vocabulary entity. Starting the key with lowercase letter means that is a vocabulary property.Nathanaelnathanial
ty, I hadn't heard of that convention beforeBrannan
After some long while, I updated this answer with considerations on the issue mentioned up by @BrannanNathanaelnathanial
CamelCase and camelCase are both camel case, the former is sometimes called UpperCamelCase or ProperCase. See en.wikipedia.org/wiki/Camel_caseLusty
I think google doesn't have a standard, the places API use snake_case for example. developers.google.com/places/web-service/searchEvanston
The google maps mentioned above is a JavaScript library using camelCase while the google places as mentioned by @DavidMartinez is a web service that can return json-formatted data is of snake_case. I agree, maybe google doesn't have a standard naming convention for JSON.Nathanaelnathanial
I disagree with these ideas, simply because Python backend > Java frontend should be camelCase, but then you add Python frontend and you have compromised backend and one frontend. It should be how backend has it by "standard". Frontend parsers have it easier to adapt anywayAmeeameer
@BojanKogoj I also doubted that part of my answer. Your comment verifies that the answer had awful flaws. I will make edits on that part.Nathanaelnathanial
My concern here is that there is reference to "your technology" stack. A producer of JSON especially if to served up by a HTTP server should have no knowledge of who or what is consuming it, or for what reasons. If JSON is used as a method of communication between many producers and consumers, then the technology stack of the producer should not be a consideration.Magdalenemagdalenian
@RobbieWareham I somehow agree on that. The thing here is that "by standards" there isnt an official naming convention. So with that, maybe one should opt for "by de facto" which is to look at the technology stack. I think looking into the technology stack is the best way to go. Take a look at facebook, did they historically honor JavaScript and use snakeCase? Nah! They chose to stick with PHP's snake_case.Nathanaelnathanial
@AbelMelquiadesCallejo Fair point, and possibly reasons for an official naming convention. It would make all this easier!Magdalenemagdalenian
While I somewhat agree with your answer. I'm not comfortable with choice reasons being "make sense" and "screw front end". Big reasons why back-end naming conventions have more weight in JSON naming style is because it naturally tend to create more than read these structs, and also matching naming style cuts A LOT of silly mapping code, making things simpler in a delicate piece of the app. Front-end frameworks and libs are more flexible in that aspect and mistakes would "just" result in a UI bug.Spivey
Also public API's play a big role, where they natural choice is obviously go rather with the same naming convention of the language that manipulates than complicating things.Spivey
C# is conventionally camelCased so it should be pretty similar to those above with Java entriesNathanaelnathanial
the official RFC does not talk about any convention: tools.ietf.org/html/rfc8259Favored
@DanieleDellafiore thats what I wrote in the first statement.Nathanaelnathanial
There's also CLI, which is overwhelmingly kebab case. I always kebab case for CLI and then convert to the relevant casing (snake or camel) when producing JSON.Conaway
@Conaway I'm not so sure about that kebab-case CLI. Are you referring to shell or bash? AFAIK, the dash sign for them is a subtraction operator. Also, this is a bit confusing because even the PLs I listed all have CLI counterparts which are not kebab-case related. Much better if you could mention the binary/library/tool you are using.Nathanaelnathanial
I mean command line arguments. They are like --a-b-cConaway
P
353

There is no SINGLE standard, but I have seen 3 styles you mention ("Pascal/Microsoft", "Java" (camelCase) and "C" (underscores, snake_case)) -- as well as at least one more, kebab-case like longer-name).

It mostly seems to depend on what background developers of the service in question had; those with c/c++ background (or languages that adopt similar naming, which includes many scripting languages, ruby etc) often choose underscore variant; and rest similarly (Java vs .NET). Jackson library that was mentioned, for example, assumes Java bean naming convention (camelCase)

UPDATE: my definition of "standard" is a SINGLE convention. So while one could claim "yes, there are many standards", to me there are multiple Naming Conventions, none of which is "The" standard overall. One of them could be considered the standard for specific platform, but given that JSON is used for interoperability between platforms that may or may not make much sense.

Perambulator answered 9/6, 2011 at 16:53 Comment(8)
Sticking with the background of the devs is important, but JSON sticks with the Javascript standard. Your first statement isn't quite correct. But definately stick with the naming conventions of your team.Walcoff
It would be interesting to see some statistics, as there is constant friction between people who claim connection between JSON and Javascript (beyond just historical heritage), and those who think there is little currently that connects JSON to Javascript. I belong to the latter camp. But I would be interested in knowing relative usage patterns.Perambulator
@Perambulator C# uses PascalCase in the majority of cases, not camelCase.Yockey
@Yockey yes. What is your point? (also, pascal-case sometimes called "upper camel case")Perambulator
@Perambulator would you consider updating your answer to include mention of Googles Style GuideHoagy
Can I use all caps like eg: "ROLLNO": 12345?Microchemistry
@mannedear nothing in JSON spec prevents that so sure. It could be considered yet another naming convention. :)Perambulator
JSON case conventions like camelCase, snake_case, and their variations pose no issues for deserialization in ECMAscript-type languages (Java, C#, JavaScript). While camelCase and snake_case convert seamlessly to object properties, kebab-case might challenge applications with limited deserialization control, e.g. only a subset of Java or C# is allowed. It's better suited for map or dictionary keys than direct object properties. Consider the consuming app's deserialization capabilities when choosing case conventions; snake_case and camelCase are generally friendlier options.Examen
G
22

Notably for me on NodeJS, if I'm working with databases and my field names are underscore separated, I also use them in the struct keys.

This is because db fields have a lot of acronyms/abbreviations so something like appSNSInterfaceRRTest looks a bit messy but app_sns_interface_rr_test is nicer.

In Javascript variables are all camelCase and class names (constructors) are ProperCase, so you'd see something like

var devTask = {
        task_id: 120,
        store_id: 2118,
        task_name: 'generalLedger'
    };

or

generalLedgerTask = new GeneralLedgerTask( devTask );

And of course in JSON keys/strings are wrapped in double quotes, but then you just use the JSON.stringify and pass in JS objects, so don't need to worry about that.

I struggled with this a bit until I found this happy medium between JSON and JS naming conventions.

Glucoprotein answered 1/5, 2014 at 20:4 Comment(2)
same here. Receiving JSON with snake_case at Android client looks awkward !! Also database doesn't differentiate casing for the column names, so snake_case seems to be best for database.Nantucket
@Nantucket JSON in Java is not intrinsic in its core. Java only uses external packages for parsing Java e.g. org.json , gson. Recieving snake_case data doesn't hurt that much like so... JSONObject.get('snake_case_key_here')Nathanaelnathanial
R
8

Seems that there's enough variation that people go out of their way to allow conversion from all conventions to others: http://www.cowtowncoder.com/blog/archives/cat_json.html

Notably, the mentioned Jackson JSON parser prefers bean_naming.

Repugnance answered 4/4, 2011 at 19:51 Comment(1)
Minor correction: Jackson defaults to Java bean naming convention, which is (lower) Camel Case, like beanNaming.Perambulator
N
0

I think that there isn't a official naming convention to JSON, but you can follow some industry leaders to see how it is working.

Google, which is one of the biggest IT company of the world, has a JSON style guide: https://google.github.io/styleguide/jsoncstyleguide.xml

Taking advantage, you can find other styles guide, which Google defines, here: https://github.com/google/styleguide

Nitaniter answered 15/5, 2016 at 22:6 Comment(0)
F
0

As others have stated there is no standard so you should choose one yourself. Here are a couple of things to consider when doing so:

  1. If you are using JavaScript to consume JSON then using the same naming convention for properties in both will provide visual consistency and possibly some opportunities for cleaner code re-use.

  2. A small reason to avoid kebab-case is that the hyphens may clash visually with - characters that appear in values.

    {
      "bank-balance": -10
    }
    
Fsh answered 6/7, 2018 at 15:51 Comment(2)
snake_case uses underscores, not dashes.Present
a reason to avoid kebab-case is that they're not treated as one word. so you cannot e.g. double click with the mouse to select the entire key.Whiny

© 2022 - 2024 — McMap. All rights reserved.