I have this format of JSON output but I could not figure out how to check the key and the value. Here is my JSON output:
[
{"msgone":
{"msgId":"1",
"custName":"MYCUST"}
},
{"msgtwo":
{"msgId":"2",
"custName":"MYCUST"}
},
{"msgtwo":
{"msgId":"2",
"custName":"MYCUST"}
}
]
There you go. Now what I want to do is first I want to loop each of them and check if it is msgone
then do something. If it is msgtwo
then do something. If let's say current loop is msgone
then I want to take all the object msgId
and custName
to do further processing.
This is part of the code that I have at this moment:
success: function(msg){
$('#res').val(msg); //just echo to debug
var returnedRep = $.parseJSON(msg);
$.each(returnedRep, function(index, value) {
if(returnedRep[index] === 'msgone'){
//give me the values
}
if(returnedRep[index] === 'msgtwo'){
//give me the values
}
});
}
Appreciate your feedback on this. I am new to JSON. But with different form of it, I could not able how to read through it. Thank you.
UPDATE: This is how I code that outputs my JSON data:
$globArr [] = array(
"type" => "msgone",
"data" => array(
"msgId" => $details[0],
"custName" => $details[1]
)
);
Each time the message comes, I will store them in $globArr
. I could not figure out how to make structure like @DemoUser suggested. Anybody please help me.
If you create the json data by yourself, then you could make the data consistent, something like:
[
{
"type": "msgone",
"data" : [
{
"msgId":"1",
"custName":"MYCUST"
}
]
},
{
"type" : "msgtwo",
"data" : [
{
"msgId":"2",
"custName":"MYCUST"
},
{
"msgId":"2",
"custName":"MYCUSTSOME"
},
]
}
]
and you could parse it as:
success: function(msg){
$('#res').val(msg); //just echo to debug
var returnedRep = $.parseJSON(msg);
$.each(returnedRep, function(key, val) {
var type = val.type;
var dataArr = val.data;
$.each(dataArr, function(idx, v) {
alert(v.msgId);
});
});
}
Update for json structure in PHP:: (this gives you the required format like i mentioned),
$arr = array();
$arr[] = array(
"type" => "msgOne",
"data" => array(
array("msgId" => 1, "custName" => "Some name")
)
);
$arr[] = array(
"type" => "msgTwo",
"data" => array(
array("msgId" => 2, "custName" => "Some second name"),
array("msgId" => 3, "custName" => "Some third name"),
)
);
echo json_encode($arr);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.