How to Check If a Key Exists in a Serialized JSON String Using JavaScript?

In JavaScript, there are several ways in which you can check if a key exists in a serialized JSON string. Some of the most notable ways, where you don't have to parse the JSON string, are as follows:

  1. Using String.prototype.includes();
  2. Using a Regular Expression.

You can, of course, also parse the serialized JSON string first by using the JSON.parse() method, and then check if the key exists in the resulting JSON object.

Using String.prototype.includes()

The simplest way to check if a specific key exists in a serialized JSON string without needing to parse it first is by checking the key with the String.prototype.includes() method in the following format:

"keyName":

For example:

// ES6+
const json = '{"name":"John","age":23,"city":null}';
const hasCity = json.includes('"city":');

console.log(hasCity); // true

You can also dynamically create the key by using string interpolation with backticks (``), for example, like so:

// ES6+
const json = '{"name":"John","age":23,"city":null}';
const keyName = 'city';
const hasCity = json.includes(`"${keyName}":`);

console.log(hasCity); // true

Using a Regular Expression

You can use a regular expression, along with the RegExp.prototype.test() method, to check if a specific key exists in a serialized JSON string without needing to parse it first. To do so, you can use the following regular expression with the name of the key between double quotes:

"keyName"\:.+

For example, you can use the literal regular expression notation to check if a certain key exists in the string, like so:

const json = '{"name":"John","age":23,"city":null}';
const hasCity = /"city"\:.+/.test(json);

console.log(hasCity); // true

You can also dynamically create the regular expression by using the RegExp() constructor instead of the literal notation, for example, like so:

const json = '{"name":"John","age":23,"city":null}';
const keyName = 'city';
const regex = new RegExp(`"${keyName}"\:.+`);
const hasCity = regex.test(json);

console.log(hasCity); // true

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.