在PHP中解析此JSON OBJECT

时间:2017-08-10 21:27:05

标签: php json

我将通过HTTP POST接收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 }]}

我想将它解析为3个不同的变量$ username,$ password和$ q

从这个例子来看,这就是我所期望的:

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 }]

2 个答案:

答案 0 :(得分:1)

首先,您的示例不是有效的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_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;

答案 1 :(得分:0)

示例中的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";