[英]Parse this JSON OBJECT in PHP
I am going to be receiving a JSON object via HTTP POST and I am finding it difficult to parse it. 我将通过HTTP POST接收JSON对象,并且发现很难解析它。 This is what the JSON object looks like: JSON对象如下所示:
{ login: {username: 123, password: 456} }, questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]}
I want to parse it into 3 different variables $username, $password and $q 我想将其解析为3个不同的变量$ username,$ password和$ q
From the example, this is what I expect it to be: 从示例中,这就是我期望的结果:
echo $username // **output:** 123
echo $password // **output:** 456
echo $q //**output:** questions:[{ name: "insomnia", type: "boolean", problem: true, question: "Did you experience insomnia?", answer: null},{ name: "go-to-bed", type: "amount", problem: false, question: "When did you go to bed?", answer: null }]
First your example is not a valid json. 首先,您的示例不是有效的json。 Here the valid one: 这里是有效的:
[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]
Next you can use json_decode
from a string: 接下来,您可以从字符串中使用json_decode
:
$x = '[{
"login": {
"username": 123,
"password": 456
},
"questions": [{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
}, {
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}]
}]';
$q = json_decode($x);
print_r($q);
echo $q[0]->login->username;
The JSON in the example is invalid, I fixed it and put together a test, I think this is what you're looking for. 该示例中的JSON无效,我对其进行了修复并进行了测试,我认为这就是您想要的。
<?php
$json = <<<JSON
{
"login": {
"username": 123,
"password": 456
},
"questions": [
{
"name": "insomnia",
"type": "boolean",
"problem": true,
"question": "Did you experience insomnia?",
"answer": null
},
{
"name": "go-to-bed",
"type": "amount",
"problem": false,
"question": "When did you go to bed?",
"answer": null
}
]
}
JSON;
$decoded = json_decode($json);
$username = $decoded->login->username;
$password = $decoded->login->password;
// Re-encode questions to a JSON string
$q = json_encode($decoded->questions);
echo $username."\n";
echo $password."\n";
echo $q."\n";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.