4

I have the following array that I output using echo json_encode(array);

Array (
  [0] => Array (
  [id] => 85
  [name] => yeyery
  [area_xy] => {"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}}
  )
)

And this is the output that I get:

[
   {
      "id":"85",
      "name":"yeyery",
      "area_xy":"{\"type\": \"rectangle\",\"coordinates\": {\"point1\":\"22.272219163607744:114.13580417633057\",\"point2\":\"22.275753627993897:114.1413402557373\",\"point3\":\"22.27297371968214:114.14400100708008\",\"point4\":\"22.270868895211578:114.13910865783691\"}}",
   }
]

But the intended output is this:

[
   {
      "id":"85",
      "name":"yeyery",
      "area_xy":{"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}},
   }
]

After "area_xy" I do not want to have double quotes that wraps my nested JSONs.

James Wong
  • 4,529
  • 4
  • 48
  • 65

1 Answers1

5

The initial output is misleading; you should use var_export, and you'd see that the area_xy value is already a string:

array (
  0 => 
  array (
    'id' => 85,
    'name' => 'yeyery',
    'area_xy' => '{"type": "rectangle","coordinates": {"point1":"22.272219163607744:114.13580417633057","point2":"22.275753627993897:114.1413402557373","point3":"22.27297371968214:114.14400100708008","point4":"22.270868895211578:114.13910865783691"}}',
  ),
)

To rectify that, decode it first, and then encode the whole shebang:

$arr[0]['area_xy'] = json_decode($arr[0]['area_xy']);
echo json_encode($arr, JSON_PRETTY_PRINT);
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469