我有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"
}
]
我试图这样做
componet.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中编写代码的原因。
答案 0 :(得分:5)
您始终可以创建模型:
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);
OR
// Assume you have received the json in object form in 'resultlist' variable
let dataList = <Array<UserDetails>>resultlist;
快乐编码!
答案 1 :(得分: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数据中的属性名称,并且可以正确,轻松地处理数据,请在此链接上查阅more infos
答案 2 :(得分:0)
this.userData["role"] = this.user.role
应该是this.userData["role"] = this.role
答案 3 :(得分: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;