As an empty string is not valid JSON it would be incorrect for JSON.parse('') to return null because "null" is valid JSON. e.g.

JSON.parse("null");

returns null. It would be a mistake for invalid JSON to also be parsed to null.

While an empty string is not valid JSON two quotes is valid JSON. This is an important distinction.

Which is to say a string that contains two quotes is not the same thing as an empty string.

JSON.parse('""');

will parse correctly, (returning an empty string). But

JSON.parse('');

will not.

Valid minimal JSON strings are

The empty object '{}'

The empty array '[]'

The string that is empty '""'

A number e.g. '123.4'

The boolean value true 'true'

The boolean value false 'false'

The null value 'null'

Answer from bhspencer on Stack Overflow
🌐
Hiredgun
hiredgun.tech › home › apis › handling empty json strings
Handling Empty JSON Strings - hiredgun.tech
December 8, 2024 - The JSON is reduced to just the content I require by use of the Compose action – see my recent post Simplify JSON Content Before Parsing for details on how to do this. The simplified JSON is subsequently parsed by the Parse JSON action, and the output is entered into Dataverse. Below are 2 returned objects. The first has a complete set of data but the second returns an empty string for Registration Year and Company Status.
Discussions

Best Practices to send for Empty Values of a JSON API?
On July 1st, a change to Reddit's API pricing will come into effect. Several developers of commercial third-party apps have announced that this change will compel them to shut down their apps. At least one accessibility-focused non-commercial third party app will continue to be available free of charge. If you want to express your strong disagreement with the API pricing change or with Reddit's response to the backlash, you may want to consider the following options: Limiting your involvement with Reddit, or Temporarily refraining from using Reddit Cancelling your subscription of Reddit Premium as a way to voice your protest. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/learnprogramming
16
16
April 22, 2024
Send empty object if json string is null
I’m trying to detect if a JSON string exists (i.e. not null) and send an empty json object {} instead. First, I use Transform to JSON to turn an object into JSON Then, I use an if statement to check if the object exists or not But it’s still being sent as null PS, I’ve tried using three ... More on community.make.com
🌐 community.make.com
8
0
July 8, 2024
export - How can I create an empty JSON object? - Mathematica Stack Exchange
Newer Versions means >= 10.1, 10.0.x ... empty lists and objects in Mathematica... As mentioned by Kuba in a comment the export format "JSON" has some deficiancies which are overcome by the export format "RawJSON" which seem to work better than "JSON" in many respects, especially when working with Associations... Kubas example where "JSON" ... More on mathematica.stackexchange.com
🌐 mathematica.stackexchange.com
June 13, 2014
What is the minimum valid JSON?
What strings are the minimum possible valid JSON? ... I've just tried on jsonlint, and it now accepts all of these. It must have been a bug that it previously rejected the first 3. ... Something else I've just discovered is that the Newtonsoft JSON library accepts an empty string and returns ... More on stackoverflow.com
🌐 stackoverflow.com
🌐
JSON for Modern C++
json.nlohmann.me › api › basic_json › empty
empty - JSON for Modern C++
#include <iostream> #include <nlohmann/json.hpp> using json = nlohmann::json; int main() { // create JSON values json j_null; json j_boolean = true; json j_number_integer = 17; json j_number_float = 23.42; json j_object = {{"one", 1}, {"two", 2}}; json j_object_empty(json::value_t::object); json j_array = {1, 2, 4, 8, 16}; json j_array_empty(json::value_t::array); json j_string = "Hello, world"; // call empty() std::cout << std::boolalpha; std::cout << j_null.empty() << '\n'; std::cout << j_boolean.empty() << '\n'; std::cout << j_number_integer.empty() << '\n'; std::cout << j_number_float.empty() << '\n'; std::cout << j_object.empty() << '\n'; std::cout << j_object_empty.empty() << '\n'; std::cout << j_array.empty() << '\n'; std::cout << j_array_empty.empty() << '\n'; std::cout << j_string.empty() << '\n'; }
🌐
Reddit
reddit.com › r/learnprogramming › best practices to send for empty values of a json api?
r/learnprogramming on Reddit: Best Practices to send for Empty Values of a JSON API?
April 22, 2024 -

What do you choose? Getting lots of conflicting answers.

  1. Null

  2. Undefined (Omitted from JSON)

  3. Empty of that type?

    1. String = ""

    2. Number = 0

    3. Boolean = false

    4. Array = []

    5. Object = {}

CMS JSON API to be consumed by JS Framework Frontend

🌐
Make Community
community.make.com › questions
Send empty object if json string is null - Questions - Make Community
July 8, 2024 - I’m trying to detect if a JSON string exists (i.e. not null) and send an empty json object {} instead. First, I use Transform to JSON to turn an object into JSON Then, I use an if statement to check if the object…
Top answer
1 of 2
11

You can define your own object and tell Mathematica to interpret it as JSON object.

Dummy export to load relevant contexts:

In[1]:= ExportString["", "JSON"];

Tell Mathematica to interpret JSONObject symbol as possible head of JSON objects:

In[2]:= ClearAll[JSONObject]
         System`Convert`JSONDump`$JSONObjectHead = JSONObject;

Now you can use JSONObject anywhere in exported expression:

In[4]:= ExportString[JSONObject[], "JSON"]
Out[4]= {}

In[5]:= ExportString[{"a" -> JSONObject[]}, "JSON"]
Out[5]= {"a" : {}}

In[6]:= ExportString[JSONObject["a" -> JSONObject["b" -> Null]], "JSON"]
Out[6]= {"a" : {"b" : null}}

How it works

Internally export to JSON is handled by System`Convert`JSONDump`exportJSON function which is just a wrapper for System`Convert`JSONDump`iexportJSON. The latter calls System`Convert`JSONDump`toString which does the real conversion and, among others, includes following definitions (System`Convert`JSONDump` context removed from symbol names):

toString[x_?($JSONObjectHead =!= List && MatchQ[#1, $JSONObjectHead[]]&), `t_Integer] := {}

toString[x_?($JSONObjectHead =!= List && Head[#1] === $JSONObjectHead && Length[#1] =!= 0&), t_Integer] := toString[List @@ x, t]

that use $JSONObjectHead.

How to find out, how exporting works

You can start by tracing evaluation of export expression:

TracePrint[
    ExportString["mySpecialString", "JSON"],
    _[___, "mySpecialString", ___]
]

You'll find that System`Convert`JSONDump` context looks interesting. For fast overview of it's symbols you can look at:

Names["System`Convert`JSONDump`*"] // TableForm

Real fun will start if you use this great spelunking tool:

Get["https://raw.githubusercontent.com/szhorvat/Spelunking/master/Spelunking.m"]

Pick a function, from printed trace that looks promising:

Spelunk["System`Convert`JSONDump`exportJSON"]

and dig deeper by clicking on links to functions that you see in the trace.

About spelunking tool I learned from one of halirutans answers.

2 of 2
8

For newer versions exporting an empty Association does what you want:

ExportString[<||>, "JSON"]

Newer Versions means >= 10.1, 10.0.x versions did export empty Associations to empty lists, of course the new behavior is a much better match for the distinction of JavaScript empty lists and objects in Mathematica...

As mentioned by Kuba in a comment the export format "JSON" has some deficiancies which are overcome by the export format "RawJSON" which seem to work better than "JSON" in many respects, especially when working with Associations...

Kubas example where "JSON" gives an error while "RawJSON" works as intendes was:

ExportString[<|"test" -> <||>|>, "RawJSON"]
🌐
Quora
quora.com › How-do-you-declare-an-empty-JSON-in-Python
How to declare an empty JSON in Python - Quora
Answer (1 of 4): JSON is a serialization format that can represent certain kinds of objects as strings. An empty string is not a valid JSON representation of anything. If you try to decode an empty string using Python's standard [code ]json[/code] module, you'll get an error: [code]>>> import j...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON › parse
JSON.parse() - JavaScript - MDN Web Docs
For other valid JSON values, reviver works similarly and is called once with an empty string as the key and the value itself as the value. If you return another value from reviver, that value will completely replace the originally parsed value. This even applies to the root value. For example:
Find elsewhere
Top answer
1 of 8
213

At the time of writing, JSON was solely described in RFC4627. It describes (at the start of "2") a JSON text as being a serialized object or array.

This means that only {} and [] are valid, complete JSON strings in parsers and stringifiers which adhere to that standard.

However, the introduction of ECMA-404 changes that, and the updated advice can be read here. I've also written a blog post on the issue.


To confuse the matter further however, the JSON object (e.g. JSON.parse() and JSON.stringify()) available in web browsers is standardised in ES5, and that clearly defines the acceptable JSON texts like so:

The JSON interchange format used in this specification is exactly that described by RFC 4627 with two exceptions:

  • The top level JSONText production of the ECMAScript JSON grammar may consist of any JSONValue rather than being restricted to being a JSONObject or a JSONArray as specified by RFC 4627.

  • snipped

This would mean that all JSON values (including strings, nulls and numbers) are accepted by the JSON object, even though the JSON object technically adheres to RFC 4627.

Note that you could therefore stringify a number in a conformant browser via JSON.stringify(5), which would be rejected by another parser that adheres to RFC4627, but which doesn't have the specific exception listed above. Ruby, for example, would seem to be one such example which only accepts objects and arrays as the root. PHP, on the other hand, specifically adds the exception that "it will also encode and decode scalar types and NULL".

2 of 8
55

There are at least four documents which can be considered JSON standards on the Internet. The RFCs referenced all describe the mime type application/json. Here is what each has to say about the top-level values, and whether anything other than an object or array is allowed at the top:

RFC-4627: No.

A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.

A JSON text is a serialized object or array.

JSON-text = object / array

Note that RFC-4627 was marked "informational" as opposed to "proposed standard", and that it is obsoleted by RFC-7159, which in turn is obsoleted by RFC-8259.

RFC-8259: Yes.

A JSON text is a sequence of tokens. The set of tokens includes six structural characters, strings, numbers, and three literal names.

A JSON text is a serialized value. Note that certain previous specifications of JSON constrained a JSON text to be an object or an array. Implementations that generate only objects or arrays where a JSON text is called for will be interoperable in the sense that all implementations will accept these as conforming JSON texts.

JSON-text = ws value ws

RFC-8259 is dated December 2017 and is marked "INTERNET STANDARD".

ECMA-262: Yes.

The JSON Syntactic Grammar defines a valid JSON text in terms of tokens defined by the JSON lexical grammar. The goal symbol of the grammar is JSONText.

Syntax JSONText :

JSONValue

JSONValue :

JSONNullLiteral

JSONBooleanLiteral

JSONObject

JSONArray

JSONString

JSONNumber

ECMA-404: Yes.

A JSON text is a sequence of tokens formed from Unicode code points that conforms to the JSON value grammar. The set of tokens includes six structural tokens, strings, numbers, and three literal name tokens.

🌐
IBM
ibm.com › docs › en › baw › 19.0.0
Handling JSON null and empty arrays and objects
August 11, 2022 - Handling null and empty arrays and objects used in JSON data is described.
🌐
GeeksforGeeks
geeksforgeeks.org › python › check-if-python-json-object-is-empty
Check If Python Json Object is Empty - GeeksforGeeks
July 23, 2025 - In this example, below code defines a function `is_json_empty` that takes a JSON object as input and returns `True` if its length is 0, indicating an empty JSON object.
🌐
JSON Formatter
jsonformatter.org › 8f8c59
empty
It uses $.parseJSON and JSON.stringify to beautify JSON easy for a human to read and analyze. Download JSON, once it's created or modified and it can be opened in Notepad++, Sublime, or VSCode alternative. JSON Format Checker helps to fix the missing quotes, click the setting icon which looks like a screwdriver on the left side of the editor to fix the format. ... JSON Example with all data types including JSON Array.
🌐
ServiceNow Community
servicenow.com › community › sysadmin-forum › syntaxerror-empty-json-string-nativejson-line › m-p › 2622772
SyntaxError: Empty JSON string / NativeJSON ... - ServiceNow Community
June 18, 2024 - The error description is "SyntaxError: Empty JSON string (sys_script_include.d2426c9ec0a8016501958bf2ac79c775.script; line 155) "
🌐
Wordpress
paulzipblog.wordpress.com › 2020 › 08 › 16 › oracle-json-and-empty-strings
Oracle JSON and Empty Strings “” | Paulzip's Oracle Blog
August 16, 2020 - Oracle's support of JSON from v12 onwards is pretty comprehensive, however it does lack support for generating empty string "" values. Oracle is very clear about this limitation in their JSON documentation : Because Oracle SQL treats an empty string as NULL there is no way to construct an empty JSON string ("").Oracle Documents : Generation of…
🌐
JAXB
javaee.github.io › javaee-spec › javadocs › javax › json › JsonObject.html
JsonObject (Java(TM) EE 8 Specification APIs)
JsonReader jsonReader = Json.createReader(...); JsonObject object = jsonReader.readObject(); jsonReader.close(); It can also be built from scratch using a JsonObjectBuilder. For example 1: An empty JSON object can be built as follows:
Top answer
1 of 8
39

TLDR; Remove null properties

The first thing to bear in mind is that applications at their edges are not object-oriented (nor functional if programming in that paradigm). The JSON that you receive is not an object and should not be treated as such. It's just structured data which may (or may not) convert into an object. In general, no incoming JSON should be trusted as a business object until it is validated as such. Just the fact that it deserialized does not make it valid. Since JSON also has limited primitives compared to back-end languages, it is often worth it to make a JSON-aligned DTO for the incoming data. Then use the DTO to construct a business object (or error trying) for running the API operation.

When you look at JSON as just a transmission format, it makes more sense to omit properties that are not set. It's less to send across the wire. If your back-end language does not use nulls by default, you could probably configure your deserializer to give an error. For example, my common setup for Newtonsoft.Json translates null/missing properties to/from F# option types only and will otherwise error. This gives a natural representation of which fields are optional (those with option type).

As always, generalizations only get you so far. There are probably cases where a default or null property fits better. But the key is not to look at data structures at the edge of your system as business objects. Business objects should carry business guarantees (e.g. name at least 3 characters) when successfully created. But data structures pulled off the wire have no real guarantees.

2 of 8
23

Going with an empty string is a definitive no. Empty string still is a value, it is just empty. No value should be indicated using a construct which represents nothing, null.

From API developer's point of view, there exist only two types of properties:

  • required (these MUST have a value of their specific type and MUST NOT ever be empty),
  • optional (these MAY contain a value of their specific type but MAY also contain null.

This makes it quite clear that when a property is mandatory, ie. required, it can never be null.

On the other hand, should an optional property of an object not be set and left empty, I prefer to keep them in the response anyway with the null value. From my experience it makes it easier for the API clients to implement parsing, as they're not required to check whether a property actually exists or not, because it's always there, and they can simply convert the response to their custom DTO, treating null values as optional.

Dynamically including/removing fields from the response forces including additional conditions on the clients.


Either way, whichever way you choose, make sure you keep it consistent and well documented. That way it really does not matter what you use for your API, as long as the behaviour is predictable.

🌐
GitHub
github.com › axios › axios › issues › 4146
JSON requests with an empty string payload have the string `""` passed instead · Issue #4146 · axios/axios
October 5, 2021 - Notice that it differs from the data parameter passed to the axios call. axios({ method: 'GET', url: 'https://api.github.com', data: '', headers: {Accept: 'application/json', "Content-Type":"application/json"} }).then(r => console.log(r.con...
Author: axios