2014-03-05 32 views
0

我正在尝试json_decode这个字符串,但它不工作,因为json键没有在它们周围引号。PHP:将引号添加到json数组中的每个键

我如何转换字符串:

{ 
    chips: [ 
     { 
      doritos: "yum", 
      fritos: -2147483648 
     } 
    ] 
} 

为有效的JSON字符串:

{ 
    "chips": [ 
     { 
      "doritos": "yum", 
      "fritos": -2147483648 
     } 
    ] 
} 
+0

^因为json_decode不解析它 – user2217162

+1

@skrilled - 在JavaScript中是正确的,在JSON中它不是。 – Quentin

+0

你从哪里得到这个糟糕的JSON?你能修复源代码吗? –

回答

0

你可以试试这个:

$string = preg_replace(array('chips','doritos', 'fritos'), array('"chips"', '"doritos"', '"fritos"'), $string); 

echo $string; 
+0

问题是,我不知道所有真正的键名。 – user2217162

1

不是最优的,但应该工作或成为一个开始:

$new_json = preg_replace('/([\w\d]+): /', '"$1": ', $old_json); 
相关问题