PHP将引号添加到json_decode数组 [英] PHP add quotes to array for json_decode

查看:120
本文介绍了PHP将引号添加到json_decode数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找json_decode一个字符串,但是遇到数组元素没有引号的问题.

I'm looking to json_decode a string, but running into a problem with the array elements not having quotes.

JSON

{"Status":"DISPUTED","GUID":[]}
{"Status":"CONFIRMED","GUID":[G018712, G017623]}

PHP

$json = '{"Status":"CONFIRMED","GUID":[G018712,G017623]}';
$a = json_decode($json, true);
print $a['Status'];

结果

上面的php打印内容不会显示任何内容,因为数组中的数字中混有字母,而json_decode不喜欢它.您如何为每个数组项添加字符串,以便json_decode起作用?

The php print above won't display anything because there are letters mixed in with the numerics within the array and the json_decode doesn't like it. How would you add strings to each array item, so that json_decode will work?

推荐答案

您的json无效.应该是-

$json = '{"Status":"CONFIRMED","GUID":["G018712","G017623"]}';

$json = '{Status:"CONFIRMED",GUID:["G018712","G017623"]}';


您可以使用-


You can easily fix it using-

$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/', '"$1"', $json);


完整示例


Full example

$json = '{"Status":"CONFIRMED","GUID":[G018712,G017623]}{"Status":"CONFIRMED","GUID":[018712,a017623]}';
// fix json
$json = preg_replace('/(?<!")(?<!\w)(\w+)(?!")(?!\w)/', '"$1"', $json);
$a = json_decode($json, true);
print $a['Status'];

这篇关于PHP将引号添加到json_decode数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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