0

我有 json 数据,我想将其转换为对象格式以进行创建操作。

json

[
{
    "user": {
        "id": 83,
        "username": "das",
        "first_name": "dsafha",
        "last_name": "dfksdfk",
        "email": "sasda@gmail.com",
        "is_active": true,
        "is_superuser": false
    },
    "role": "testBu"
},
{
    "user": {
        "id": 84,
        "username": "sadfds",
        "first_name": "dshhgds",
        "last_name": "fsdjsl",
        "email": "fdjgd@gmail.com",
        "is_active": true,
        "is_superuser": false
    },
    "role": "testeditrole"
},
{
    "user": {
        "id": 86,
        "username": "fs",
        "first_name": "efhks",
        "last_name": "sofdh",
        "email": "fdshk@gmail.com",
        "is_active": true,
        "is_superuser": false
    },
    "role": "testeditrole"
},
{
    "user": {
        "id": 87,
        "username": "xz",
        "first_name": "vj",
        "last_name": "vkfd",
        "email": "sdsl@gmail.com",
        "is_active": true,
        "is_superuser": false
    },
    "role": "testeditrole"
}
]

我试着这样做

组件.ts

let user:any = {};
   user["username"] = this.user.user.email
   user["first_name"] = this.user.user.first_name
   user["last_name"]= this.user.user.last_name
   user["email"]= this.user.user.email

   this.userData["user"] = user
   this.userData["role"] = this.user.role

在将数据输入输入字段后进行安慰时,我没有得到角色数据。我确实得到了其他数据。角色数据显示为空。我确实认为这是因为我在 componet.ts 中编写代码的方式导致了问题。

4

4 回答 4

6

您始终可以创建模型:

export class User {
 id: string,
 username: string,
 first_name: string,
 last_name: string,
 email: string,
 is_active: boolean,
 is_superuser: boolean
}
    
export class UserDetails{
 user:User;
 role:string;
}

然后:

// Assume you have received the json in string form in
'resultlist' variable
let dataList = <Array<UserDetails>>JSON.parse(resultlist);

或者:

// Assume you have received the json in object form in 'resultlist' variable
let dataList = <Array<UserDetails>>resultlist;
于 2018-10-10T11:22:35.257 回答
2

我认为最好的方法是,创建一个与 JSON 结构相对应的对象,然后将数据 JSON 分配给对象的数组。

class User{
   id:string;
   username:string;
   firstName:string;
   lastName:string;
   email:string;
   isActive:boolean;
   isSuperviser:boolean;
}
class JSONData{
   user:User;
   role:string
}
 data:JSONData[] = yourJson.data;

您可以像在班级中一样调整 json 数据中的属性名称,并且可以正确轻松地处理数据,请参阅此链接以获取更多信息

于 2018-10-10T11:33:28.413 回答
0

this.userData["role"] = this.user.role应该 this.userData["role"] = this.role

于 2018-10-10T10:34:42.503 回答
0

无需转换。它已经是 json 格式,但您应该使用数组索引然后设置用户变量。

例如 :

let user:any = {};
user = this.user[arrayIndex].user;

this.userData["user"] = user
this.userData["role"] = this.user[arrayIndex].role;

如果你想从 json 数组中获取数据,你应该使用数组索引。像这样。

let user:any = {};
user = this.user[0].user;
this.userData["role"] = this.user[0].role;
于 2018-10-10T10:40:57.307 回答