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.

5
  • Is that normal there is missing commas in your JSON ? Commented Jul 16, 2019 at 11:11
  • Oops, I missed them out. Will edit the question. Commented Jul 16, 2019 at 11:12
  • key3 is not an object, it's array right? how you are getting data in key-value pair inside array? Commented Jul 16, 2019 at 11:13
  • stackoverflow.com/questions/15617164/… Commented Jul 16, 2019 at 11:16
  • typescript can't cause runtime errors - your response is not a well formed JSON. Commented Jul 16, 2019 at 11:18

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

4 Comments

Ah, I typed out the array incorrectly. I have fixed it now. I tried your suggestion but still getting the same error.
My suggestion is incomplete, so I'm not sure what you've tried or what your error is ...
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.
The json is fine. It was static json so I just wrote a python script to format it as a TypeScript array of objects.

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.