1

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.

0

2 Answers 2

3

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);

Sign up to request clarification or add additional context in comments.

Comments

2

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.