我有一个CURL请求,它将遵循标准的请求/响应,如下所示。
curl -X GET --header 'Accept: application/vnd.pager+json;version=2' --header 'Authorization: Token token=xxxxxxxxxxxxx' 'https://api.pager.com/users/12345?include%5B%5D=contact_methods
“
{
"user": {
"name": "John Smith",
"email": "john@john.com",
"time_zone": "America/Los_Angeles",
"color": "indigo",
"avatar_url": "xxxx",
"billed": true,
"role": "user",
"description": null,
"invitation_sent": false,
"contact_methods": [
{
"id": "TP3D6TTZ",
"type": "email_contact_method",
"summary": "Default",
"self": "xxxxx",
"html_url": null,
"label": "Default",
"address": "xxxxx@xxxxxx.com",
"send_short_email": false,
"send_html_email": true
},
{
"id": "TPK4ZULL",
"type": "phone_contact_method",
"summary": "Work",
"self": "xxxxxxxxx",
"html_url": null,
"label": "Work",
"address": "5557304169",
"country_code": 1,
"blacklisted": false
}
],
}
我希望它能够使用Javascript删除一些数据,并在我的项目中重新使用它们。
所以从回复中我想要的东西......
Var1 = John Smith Always the first 'name'
Var2 = email_contact_method Always the first 'type'
Var3 = xxxxx@xxxxxx.com Always the first 'address'
Var4 = phone_contact_method Always the second 'type'
Var5 = 5557304169 Always the second 'address'
我尝试了一些事情,但我只是不知道如何选择我想要的字段。任何指针都会很棒......
答案 0 :(得分:1)
您可以使用类似JSON.parse(json)
的内容var json = '{"result":true,"count":1}',
obj = JSON.parse(json);
alert(obj.count);
此链接可能对您有所帮助。 Parse JSON in JavaScript?
答案 1 :(得分:1)
您需要使用json键访问这些值。
它会是这样的:
var json = {
"user": {
"name": "John Smith",
"email": "john@john.com",
"time_zone": "America/Los_Angeles",
"color": "indigo",
"avatar_url": "xxxx",
"billed": true,
"role": "user",
"description": null,
"invitation_sent": false,
"contact_methods": [
{
"id": "TP3D6TTZ",
"type": "email_contact_method",
"summary": "Default",
"self": "xxxxx",
"html_url": null,
"label": "Default",
"address": "xxxxx@xxxxxx.com",
"send_short_email": false,
"send_html_email": true
},
{
"id": "TPK4ZULL",
"type": "phone_contact_method",
"summary": "Work",
"self": "xxxxxxxxx",
"html_url": null,
"label": "Work",
"address": "5557304169",
"country_code": 1,
"blacklisted": false
}
]
}
};
var name = json.user.name;
var type1 = json.user.contact_methods[0].type;
var address1 = json.user.contact_methods[0].address;
var type2 = json.user.contact_methods[1].type;
var address2 = json.user.contact_methods[1].address;
console.log(name, type1, address1, type2, address2);