What is the JSON Standard for an empty string or null variable?
Asked Answered
B

2

6

I'm building an application that parses a JSON template and then replaces the values of the objects with new data. My question is what is the standard way to represent empty data in JSON?

This is how I'm handling this right now:

  • an empty string is represented as " "
  • an empty int/float/double/bool/etc. is represented as NULL

Is this correct?

Buatti answered 25/8, 2017 at 13:13 Comment(2)
Setting an empty string is like enforcing a default value. So if you do this, you should do it for other types as well, int - asign a 0, bool asign false etc. However, in my opinion "empty data" should equivalent to null. So here you have to think about whether your data should be empty or not present at all, cause you can have undefined checks somewhere as well.Courtesy
Possible duplicate of Representing null in JSONGiorgia
A
7

It should be pretty straight forward.

{
  "Value1": null, 
  "Value2": null,
}

Null represents a null-able datatype so your business layer needs then to know if that is an int, double, string ...

Atonal answered 25/8, 2017 at 13:19 Comment(0)
H
0

It is entirely up to you.

The falsy values in JavaScript are:

  • false
  • null
  • undefined
  • 0
  • NaN
  • '' or ""

You can use any of these to represent an empty value. However, keep in mind that when you try to access an object's property which doesn't exist, you will get undefined. So undefined can be considered the standard null value, in a way.

Having said that, one convention is to use null so that you can distinguish a property that has been intentionally set to null from a property that is actually undefined.

Highhanded answered 25/8, 2017 at 13:25 Comment(3)
undefined is not valid JSON, and NaN isn't valid JSON either.Quillen
You're right, however if you pass any of these values to JSON.stringify() you'll always get back a string, which is valid JSONHighhanded
but JavaScript was never mentioned.Quillen

© 2022 - 2024 — McMap. All rights reserved.