technogeek1995
technogeek1995

Reputation: 3444

Always Parse JSON as Array

How do I make sure that the json variable is always an array? In my code, sometimes str is an array and sometimes it isn't. Is there a way to make sure that it's always an array?

// array
const str = '[{ "key": "value" }]';
const json = JSON.parse(str);
console.log(json);
// [{
//   key: 'value'
// }]

// json
const str = '{ "key": "value" }';
const json = JSON.parse(str);
console.log(json);

// {
//   key: 'value'
// }

// What I want to happen somehow
const str = '{ "key": "value" }';
const json = JSON.parse(str);
console.log(json);

// [{
//   key: 'value'
// }]

I could check the type of json using instanceof, but I was hoping there would be a fancy ES6 way (with spread?) happen without it giving me an array of arrays with str is wrapped in brackets.

Upvotes: 1

Views: 410

Answers (2)

Tyler Roper
Tyler Roper

Reputation: 21672

You could use concat which will either merge or wrap the parsed JSON.

const jsonObject = '{ "key": "value" }';
const result1 = [].concat(JSON.parse(jsonObject));
console.log(result1);

const jsonArray = '[{ "key": "value" }]';
const result2 = [].concat(JSON.parse(jsonArray));
console.log(result2);

Upvotes: 3

WilliamNHarvey
WilliamNHarvey

Reputation: 2485

Make into an array then flatmap it, if the original json was an array the internal array will get removed.

const str1 = '[{ "key": "value" }]';
const json1 = [JSON.parse(str1)].flatMap(x => x);
console.log(json1);

const str2 = '{ "key": "value" }';
const json2 = [JSON.parse(str2)].flatMap(x => x);
console.log(json2);

Upvotes: 2

Related Questions