Rumah > pembangunan bahagian belakang > tutorial php > [PHP]将JSON模型的数据,替换成JSON数据,该如何解决

[PHP]将JSON模型的数据,替换成JSON数据,该如何解决

WBOY
Lepaskan: 2016-06-13 13:33:48
asal
1033 orang telah melayarinya

[PHP]将JSON模型的数据,替换成JSON数据
{data:[{code:"现货黄金",newPrice:"1662.3",hight:"0",low:"0",buy:"1662.3",sell:"r1663.3",zhang:"r4.75",date:"4:59:40",open:"0",close:"1657.55"}, {code:"香港黄金",newPrice:"15384",hight:"0",low:"0",buy:"15384",sell:"r15390",zhang:"r44",date:"2:59:55",open:"0",close:"15340"}, {code:"现货白银",newPrice:"31.25",hight:"0",low:"0",buy:"31.25",sell:"r31.31",zhang:"r0.17",date:"4:56:10",open:"0",close:"31.08"}, {code:"现货白金",newPrice:"1566.75",hight:"0",low:"0",buy:"1566.75",sell:"r1576.75",zhang:"r2.01",date:"3:29:35",open:"0",close:"1564.74"}, {code:"现货钯金",newPrice:"677.23",hight:"0",low:"0",buy:"677.23",sell:"r684.23",zhang:"r9.54",date:"3:29:35",open:"0",close:"667.69"}]}


大家看好了,这是具有一个JSON数据的模型,只是键名没有引号,所以json_decode会认为它是非法的JSON数据格式。现要用正则将它替换成,且加引号。

/(?
请教各位大侠。

------解决方案--------------------

PHP code
<?php $json=<<<JSON
{data:[{code:"现货黄金",newPrice:"1662.3",hight:"0",low:"0",buy:"1662.3",sell:"r1663.3",zhang:"r4.75",date:"4:59:40",open:"0",close:"1657.55"}, {code:"香港黄金",newPrice:"15384",hight:"0",low:"0",buy:"15384",sell:"r15390",zhang:"r44",date:"2:59:55",open:"0",close:"15340"}, {code:"现货白银",newPrice:"31.25",hight:"0",low:"0",buy:"31.25",sell:"r31.31",zhang:"r0.17",date:"4:56:10",open:"0",close:"31.08"}, {code:"现货白金",newPrice:"1566.75",hight:"0",low:"0",buy:"1566.75",sell:"r1576.75",zhang:"r2.01",date:"3:29:35",open:"0",close:"1564.74"}, {code:"现货钯金",newPrice:"677.23",hight:"0",low:"0",buy:"677.23",sell:"r684.23",zhang:"r9.54",date:"3:29:35",open:"0",close:"667.69"}]}
JSON;

$json=preg_replace_callback('/(,|,?\s*?{)\b(\w+):/','callback',$json);
print_r(json_decode($json,true));

function callback($v){
    return "{$v[1]}\"{$v[2]}\":";
}
<br /><font color="#e78608">------解决方案--------------------</font><br>$json=preg_replace('/(,|,?\s*?{)\b(\w+):/', '$1"$2":',$json);<br>print_r(json_decode($json,true));<br>
<br><font color="#e78608">------解决方案--------------------</font><br>还是老大威武<br>2楼的修改下就可以了  ({|,)([^:\s]*)(?=:)
Salin selepas log masuk
探讨

楼上的,非常棒,是我要的结果。

想请问一下:用正则(?

------解决方案--------------------
探讨

楼上的,非常棒,是我要的结果。

想请问一下:用正则(?
Label berkaitan:
sumber:php.cn
Kenyataan Laman Web ini
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn
Tutorial Popular
Lagi>
Muat turun terkini
Lagi>
kesan web
Kod sumber laman web
Bahan laman web
Templat hujung hadapan