0

I have a large json object that looks like this:

{
     "item1": {
         "key1": "val1",
         "key2": "val2",
         "key3": [
             "val4",
             "val5",
         ]
    },
    {
     "item2": {
         "key1": "val1",
         "key2": "val2",
         "key3": [
             "val3",
             "val4",
         ]
    }

    ... etc ...
}

I created an interface:

interface MyObj {
    key1: string;
    key2: string;
    key3: string[];
}

Then try to parse the json:

const myObj[]: {string: Myobj[]} = JSON.parse(response);

But I get the error SyntaxError: Unexpected token o in JSON at position 1. I have checked response in a json validator and it passes.

I want to parse response into an array of MyObj.

alex87
  • 419
  • 3
  • 11

1 Answers1

1

Few things going wrong here, your type definition here isn't using correct TypeScript syntax

const myObj[]: {string: Myobj[]} = JSON.parse(response);
           ^^^^^^^^^^^^^^^^^^^^^
             This looks weird

Also your response object is malformed, key3 is invalid (halfway between an array and object).

Anyway, try defining the type for the response first, and then parsing:

type MyObj = {
  key1: string
  // etc ...
}

type Response = {
  [key: string]: MyObj
}

const data:Response = JSON.parse(response)
Jed Richards
  • 12,244
  • 3
  • 24
  • 35
  • Ah, I typed out the array incorrectly. I have fixed it now. I tried your suggestion but still getting the same error. – alex87 Jul 16 '19 at 11:31
  • My suggestion is incomplete, so I'm not sure what you've tried or what your error is ... – Jed Richards Jul 16 '19 at 12:57
  • Btw your error `SyntaxError: Unexpected token o in JSON at position 1` has nothing to do with TypeScript, it sounds like your actual JSON file is malformed. – Jed Richards Jul 16 '19 at 12:58
  • The json is fine. It was static json so I just wrote a python script to format it as a TypeScript array of objects. – alex87 Jul 16 '19 at 14:30