I'd check the constructor attribute.

e.g.

var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.

Answer from Programming Guy on Stack Overflow
🌐
Reddit
reddit.com › r/learnprogramming › what is json and what does it have to do with javascript?
r/learnprogramming on Reddit: What is JSON and what does it have to do with Javascript?
March 31, 2022 -

Hi! I'm looking to dive back into Javascript after a 10+ year hiatus (learned some during college) in order to build out a basic piece of software using a WebSocket for a lighting control system. I notice that most of it can be done with Javascript, but every now and then there are JSON calls. Looking at JSON's wiki page, I notice it's an acronym "JavaScript Object Notation" so obviously has lots to do with Javascript, but apparently it's also " a language-independent data format." (whatever that means).

Any indications if I'll need to be proficient with JSON to work with the WebSocket? If so, any recommendations for resources to get started? Thank you!

Top answer
1 of 5
4
I notice it's an acronym "JavaScript Object Notation" so obviously has lots to do with Javascript, but apparently it's also " a language-independent data format." (whatever that means). It means that the syntax of JSON is based on the way you construct objects in JavaScript, but it exists independently from JS. It's a data exchange format. Similar to XML. It's just a way to use text to structure data. JSON isn't a language that really requires proficiency. For one thing, it's not a programming language; it doesn't convey logic. It's just data. And it's quite simple. There are only four data types in JSON: string, number, array, and object. Whether or not you have to be proficient with it to use WebSockets? Technically they aren't directly related. But JSON is an extremely common format to pass data over WebSockets (as well as HTTP endpoints as well).
2 of 5
3
JSON came from JavaScript but it has nothing to do with JavaScript anymore. Have you ever used XML before? JSON is basically used for most of the same sorts of things that XML was used for. JSON is basically a handy standard format to use when sending structured data from one program to another, or when saving data to a file, or something like that. That's it. By using JSON instead of making up your own format, you make it easy for anyone to parse. JSON specifies the syntax, but not the semantics. You can decide whatever data you want to put in it. Let's say you wanted to save a list of names to a file. Using JSON, you could do it like this: ["Candace", "Maya", "Ken", "Tobias"] It looks just like you're defining an array in JavaScript, and that's the idea. Let's say you needed names and ages. You could do it like this: [ { "name": "Candace", "age": 44 }, { "name": "Maya", "age": 19 }, { "name": "Ken", "age": 35 }, { "name": "Tobias", "age": 27 } ] Should you learn JSON? Yes, but it's really not that complicated. You could read the documentation in an hour and get the hang of reading and writing JSON in your favorite language in less than a day. Sure, there's more complexity to it sometimes. If you're working with really large amounts of data, people have created all sorts of tools for manipulating large JSON files, or doing queries or transformations. If you ever have a need for those, you can learn them.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › JSON
JSON - JavaScript | MDN
JSON is a communication format, so if you use JSON, you are likely communicating with another system (HTTP request, storing in database, etc.). The best solution to choose depends on the recipient system. If the recipient system does not have same JSON-handling capabilities as JavaScript, and does not support high precision numbers, you may want to serialize the number as a string, and then handle it as a string on the recipient side.
🌐
W3Schools
w3schools.com › js › js_json.asp
JavaScript JSON
JSON stands for JavaScript Object Notation. JSON is a plain text format for storing and transporting data.

I'd check the constructor attribute.

e.g.

var stringConstructor = "test".constructor;
var arrayConstructor = [].constructor;
var objectConstructor = ({}).constructor;

function whatIsIt(object) {
    if (object === null) {
        return "null";
    }
    if (object === undefined) {
        return "undefined";
    }
    if (object.constructor === stringConstructor) {
        return "String";
    }
    if (object.constructor === arrayConstructor) {
        return "Array";
    }
    if (object.constructor === objectConstructor) {
        return "Object";
    }
    {
        return "don't know";
    }
}

var testSubjects = ["string", [1,2,3], {foo: "bar"}, 4];

for (var i=0, len = testSubjects.length; i < len; i++) {
    alert(whatIsIt(testSubjects[i]));
}

Edit: Added a null check and an undefined check.

Answer from Programming Guy on Stack Overflow
Top answer
1 of 16
497

Use JSON.parse

function isJson(str) {
    try {
        JSON.parse(str);
    } catch (e) {
        return false;
    }
    return true;
}
2 of 16
159

Using JSON.parse() has some drawbacks:

  1. JSON.parse(1234) or
  2. JSON.parse(0) or
  3. JSON.parse(false) or
  4. JSON.parse(null)

all will return true.

function isJson(str) {
  try {
    JSON.parse(str);
  } catch (e) {
    return false;
  }  
  return true;
}

function testIsJson(value, expected) {
  console.log(`Expected: ${expected}, Actual: ${isJson(value)}`); 
}

// All of the following codes are expected to return false.
// But actually returns true.
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(false, false);
testIsJson(null, false);

Code that handles false positives

So I rewrote code in this way:

function isJson(item) {
  let value = typeof item !== "string" ? JSON.stringify(item) : item;    
  try {
    value = JSON.parse(value);
  } catch (e) {
    return false;
  }
    
  return typeof value === "object" && value !== null;
}

Testing result:

function isJson(item) {
  let value = typeof item !== "string" ? JSON.stringify(item) : item;
  try {
    value = JSON.parse(value);
  } catch (e) {
    return false;
  }

  return typeof value === "object" && value !== null;
}

function testIsJson(value, expected) {
  console.log(`Expected: ${expected}, Actual: ${isJson(value)}`);
}

const validJson = { "foo": "bar" };
const notValidJson = '{ "foo": "bar" } invalid';

// expected: true
testIsJson(validJson, true);

// expected: false
testIsJson(1234, false);
testIsJson(0, false);
testIsJson(notValidJson, false);
testIsJson(false, false);
testIsJson(null, false);

Find elsewhere
🌐
Wikipedia
en.wikipedia.org › wiki › JSON
JSON - Wikipedia
March 6, 2005 - JSON (JavaScript Object Notation, pronounced /ˈdʒeɪsən/ or /ˈdʒeɪˌsɒn/) is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of name–value pairs and ...
🌐
Medium
medium.com › @ExplosionPills › json-is-not-javascript-5de833fbe49c
JSON Is not JavaScript. (and JavaScript is not JSON) | by Andrew Crites | Medium
March 29, 2017 - Usually in the context of JavaScript code when people refer to JSON what they actually mean is a JavaScript object (or just “Object” to avoid redundancy). While it is true that JSON can be parsed into a JavaScript object in some circumstances, this doesn’t mean that they are analogous.
🌐
Oracle
oracle.com › ai database
What is JSON?
April 4, 2024 - As a result, JSON is relatively easy to learn and to troubleshoot. Although JSON has its roots in JavaScript, it has grown into a very capable data format that simplifies data interchange across diverse platforms and programming languages.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Learn_web_development › Core › Scripting › JSON
Working with JSON - Learn web development | MDN
JavaScript Object Notation (JSON) is a standard text-based format for representing structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications (e.g., sending some data from the server to the client, so it can be displayed on a web page, or ...
🌐
JSON
json.org
JSON
JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate. It is based on a subset of the JavaScript Programming Language Standard ECMA-262 3rd Edition - December 1999.
🌐
IBM
ibm.com › docs › en › baw › 23.0.x
JavaScript Object Notation (JSON) format
The JavaScript Object Notation (JSON) format is discussed.
🌐
W3Schools
w3schools.com › whatis › whatis_json.asp
What is JSON
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects. The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only.
🌐
JavaScript.info
javascript.info › tutorial › the javascript language › data types
JSON methods, toJSON
JSON is a data format that has its own independent standard and libraries for most programming languages. JSON supports plain objects, arrays, strings, numbers, booleans, and null.
🌐
Koombea
koombea.com › home › json vs. javascript: what is the difference?
JSON Vs. JavaScript: What is the Difference?
November 26, 2024 - JavaScript. JSON is short for JavaScript Object Notation. So is JSON JavaScript? Not exactly. JSON is a data format that is independent of any programming language, although it is derived from JavaScript.
🌐
JSONLint
jsonlint.com
JSONLint - The JSON Validator
There are several reasons why you should consider using JSON, the key reason being that JSON is independent of your system's programming language, despite being derived from JavaScript.
🌐
TheServerSide
theserverside.com › definition › JSON-Javascript-Object-Notation
What is JSON? - Definition from TechTarget.com
JSON (JavaScript Object Notation) is a text-based, human-readable data interchange format used to exchange data between web clients and web servers. The format defines a set of structuring rules for the representation of structured data.
🌐
Appsmith
community.appsmith.com › content › blog › javascript-objects-vs-json-explained-simply
Javascript Objects Vs JSON: Explained Simply | Appsmith Community Portal
March 26, 2024 - This flexibility makes Javascript Objects suitable for building complex data structures and functionalities within the code. JSON: Strictly a data format, JSON cannot hold methods.
🌐
DigitalOcean
digitalocean.com › community › tutorials › how-to-work-with-json-in-javascript
How To Work with JSON in JavaScript | DigitalOcean
August 26, 2021 - We’ve gone over the general format ... It is worth keeping in mind that JSON was developed to be used by any programming language, while JavaScript objects can only be worked with directly through the JavaScript programming language....
🌐
W3Schools
w3schools.com › jsref › jsref_obj_json.asp
JavaScript JSON Reference
JSON is text, and text can be transported anywhere, and read by any programming language. JavaScript Objects can be converted into JSON, and JSON can be converted back into JavaScript Objects.