簡體   English   中英

用PHP解析此JSON對象

[英]Parse this JSON OBJECT in PHP

我將通過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 }]

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

該示例中的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM