0

I am trying to check if the value in the input is Array. This is working great if the input is an array, but if the input is not an array, I get JSON errors: Uncaught SyntaxError: Unexpected token s in JSON at position 0

Any other solutions that won't throw errors and keep the code working so if it's a different input I can render something else?

function App() {
   const [input, setinput] = React.useState("");

   const handleSubmit = (event) => {
       event.preventDefault();
       let parsed = JSON.parse(input);
       let condition = Array.isArray(parsed);
       if(condition === true){
           console.log('working')

       }
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Mocha
  • 3
  • 1
  • 1
    Best solution: ensure the input is in a predictable, parsable format to begin with. Being unsure if something is JSON or not is a weird X problem. Secondary solution: `try/catch` around `JSON.parse`. – CertainPerformance Dec 02 '20 at 17:16

1 Answers1

0
Array.isArray(input)

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray

Scroll down to examples.

kmiklas
  • 13,085
  • 22
  • 67
  • 103
  • Array.isArray(input) gives a false statement, because the input looks like this "[1,2,3]" with quotation marks around it. Trying to get rid of "" Also I am trying to check if the input is parsable format first – Mocha Dec 02 '20 at 18:17
  • Well, to check if the string is an array, you could try the ``charAt`` method: ``if (str.charAt(0) === '[' && str.charAt(str.length-1) === ']') //yes, it's an array`` Not so elegant, but will work... and you should upvote my answer if it helped you. – kmiklas Dec 02 '20 at 19:07
  • Downvote please explain? I answered the question. – kmiklas Dec 02 '20 at 19:31
  • its great, for my situation the receiving object is either [] or {...} – Kaspatoo Aug 16 '22 at 13:29