php中怎么讲json字符串转json对象

查看:88
本文介绍了php中怎么讲json字符串转json对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题


类似js中

msg = eval('(' + msg + ')');

的写法

目前知道php对字符串json 使用json_decode() 返回都是null,百度不到其他方法

解决方案

<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

var_dump(json_decode($json));
var_dump(json_decode($json, true));

?>

结果分别是

object(stdClass)#1 (5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

array(5) {
    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

如果你json_decode后返回null,你是不是把字符串写成这样了"{ 'bar': 'baz' }",这个在JS里是可以正常解析成JSON的,但是PHP里面要写成'{ "bar": "baz" }',属性和值要用双引号

这篇关于php中怎么讲json字符串转json对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆