Reputation: 1207
I'm trying to convert the following JSON data from an Observable into a typescript Object but it's not converting the embedded JSON into Arrays that are in the Object model. How would I convert this multi-dimensional JSON data into an object?
JSON
[
{
"name": "Fake Name",
"data1": {
"entry1": false,
"entry2": true,
"entry3": "xyz"
},
"data2": {
"entry1": false,
"entry2": true,
},
"data3": {
"entry1": false,
"entry2": true,
"entry3": "xyz"
},
"info1": false,
"info2": "xyz"
},{...}
]
Object
export class NewObject {
public name: string;
public data1: object[];
public data2: object[];
public data3: object[];
public info1: string;
public info2: string;
constructor(name: string, data1: [], data2: [], data3: [],
info1: string, info2: string
) {
this.name = name;
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
this.info1 = info1;
this.info2 = info2;
}
}
Upvotes: 1
Views: 208
Reputation: 275
First of all the JSON string in your example is wrong on data2.entry2, the comma at the end is too much.
You can convert JSON strings to JavaScript objects with JSON.parse(). But be careful, this will not call the constructor of your TypeScript object and it will not check if any of the attributes of your objects actually exist in the JSON string.
export class NewObject {
public name: string;
public data1: object[];
public data2: object[];
public data3: object[];
public info1: string;
public info2: string;
constructor(name: string, data1: [], data2: [], data3: [],
info1: string, info2: string
) {
this.name = name;
this.data1 = data1;
this.data2 = data2;
this.data3 = data3;
this.info1 = info1;
this.info2 = info2;
}
}
const jsonstring = `
[
{
"name": "Fake Name",
"data1": {
"entry1": false,
"entry2": true,
"entry3": "xyz"
},
"data2": {
"entry1": false,
"entry2": true
},
"data3": {
"entry1": false,
"entry2": true,
"entry3": "xyz"
},
"info1": false,
"info2": "xyz"
}
]
`;
let a: NewObject[];
a = JSON.parse(jsonstring);
This is my first answer here to a question, so i don't know how to format all this correctly, but i hope it is understandable what i am trying to say :)
Upvotes: 1