JSON的encode与decode(php与json为例)
/**
* 数据库查询结果转为json
* @param object $result 数据库查询结果
*/
function encode_json($result) {
$result_array = [];
while ($row = mysqli_fetch_object($result)) {
$result_array[] = $row;
}
echo json_encode($result_array);//decode方法为json_decode($json)
}
/**
* 解析后台传回的json文档
* @param {json} 后台传回的json文档
*/
function jsonDecode(result) {
let obj = [];
let obj = result;
if (result.length === 0) {
alert("无数据!");
} else {
for (let i = 0; i < result.length; i++) {
console.log(obj[i].index-name-A+obj[i].index-name-B+obj[i].index-name-C+...);
//do something
}
}
}
注意:JSON在js中的encode与decode有自带的方法可以实现(
JSON.stringify()
与JSON.parse()
),但是由于在js中,万物皆可对象,所以没有decode也可以直接使用。/滑稽~
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有