JSON Utilities
import { isJson, objectStringToJson } from '@bbc/front-end-kit/js/utils/json';
This file contains all JSON related utility functions that help shorten the codebase and speed up development. One of the shortest ways to check is by parsing the string inside a try/catch function and catching the error gracefully, this function wraps that logic into a single line so it can be used directly inside conditionals.
isJson (str)
Detects if a given string is a json file
Parameters
str: String containing a possible json file
Returns
True if it's a string containing a json file
import { isJson } from '@bbc/front-end-kit/js/utils/json';
if (isJson(someString)) {
// treat as json
}
else {
// treat as basic string
}
objectStringToJson (str)
Converts string containing a raw javascript object definition to an actual JSON string using a regex behind the scenes.
Parameters
str: String containing the raw js object
Return
A JSON String
import { objectStringToJson } from '@bbc/front-end-kit/js/utils/json';
const str = '{ company: "BBC", location: "Mechelen" }';
console.log(objectStringToJson(str);)
// result: '{ "company": "BBC", "location": "Mechelen" }'