-1

i have try to print json response but "" are added to my json response

i tried below code php and id generated by drupal field

<?php
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo json_encode(array("php"=>$php,"id"=>10));
?>

output :

{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}

but i want output like below

{"php":{"title":"test","body":"test body"},"id":10}

i added some more code for above problem

{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}

why not remove json_encode from echo json_encode($php);

how i can get above output` second time

apaderno
  • 28,547
  • 16
  • 75
  • 90
Bhargav Chudasama
  • 6,928
  • 5
  • 21
  • 39

2 Answers2

3

You're encoding in JSON two times :

$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo $php ; // remove json_encode() here

After question edit:

$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
Syscall
  • 19,327
  • 10
  • 37
  • 52
0

You can also simply do this,

<?php
    $data = array("title"=>"test","body"=>"test body");
    echo json_encode(array("php"=>$data,"id"=>10));
?>
Keyur
  • 1,113
  • 1
  • 23
  • 42