Reputation: 432
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
.
Upvotes: 0
Views: 64
Reputation: 12437
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)
Upvotes: 1