-1

This is what I want to do. I would like to change the key inside the associative array of this below

array("role" => "annotation");

This code above returns a result of in JSON

{"role": "annotation"} 

I would like this output above to be like this output below

{role: "annotation"}
deceze
  • 510,633
  • 85
  • 743
  • 889
  • 7
    Strings values are always quoted, so `role` isn't a valid array key, while `'role'` is – Mark Baker May 28 '14 at 13:08
  • 1
    If you check the [JSON documentation](http://www.json.org/) you'll see that the last example is actually not valid JSON, the specifiers on the right should be quoted string. – scragar May 28 '14 at 13:09
  • Hey, Any reason why you want key without quote? – Jitendra Yadav May 28 '14 at 13:10
  • I need it for the Google Bar Chart. I already made the AJAX for it and I need to use the annotation role in it. My purpose is to make distance between the bars in the bar chart. – user3673534 May 28 '14 at 13:24

3 Answers3

4

JSON string keys are always quoted. If they weren't, they wouldn't be compatible with the JSON standard. There is no way to change this behavior with json_encode().

If you want JavaScript object literals, which allow for unquoted string keys, you will need to write your own code to output that, which I don't recommend.

Community
  • 1
  • 1
Brad
  • 159,648
  • 54
  • 349
  • 530
-1

Try this

$a = array($role => "annotation");

echo $a = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($a));
Kapil gopinath
  • 1,053
  • 1
  • 8
  • 18
  • This is working. Thank you but how can I modify it if it's inside an array already like this? [['sample1', 'sample2', {"role": "annotation"}]] I would like it to be like this [['sample1', 'sample2', {role: "annotation"}]] please help. – user3673534 May 28 '14 at 13:48
  • $a = array(array('sample1', 'sample2',array('role' => "annotation"))); echo $a = preg_replace('/"([^"]+)"\s*:\s*/', '$1:', json_encode($a)); – Kapil gopinath May 29 '14 at 05:22
-1

@Kapil

preg_replace('/"([^\s"]+)"\s*:\s*/', '$1:', $json);

Is a safier option.