简体   繁体   English

json返回字符串而不是对象

[英]json returning string instead of object

i have 我有

 $age = implode(',', $wage);   // which is object return:  [1,4],[7,11],[15,11]
  $ww = json_encode($age);

and then i retrieve it here 然后我在这里检索

    var age = JSON.parse(<?php echo json_encode($ww); ?>); 

so if i make 所以如果我做

   alert(typeof(<?php echo $age; ?>))   // object
   alert(typeof(age))                   //string

in my case JSON.parse retuned as string. 在我的情况下,JSON.parse重新调整为字符串。

how can i let json return as object? 我怎样才能让json返回为对象?

EDIT: 编辑:

 var age = JSON.parse(<?php echo $ww; ?>); // didnt work , its something syntax error

implode returns a string, so it is only natural that json_encode encodes it as such. implode返回一个字符串,因此json_encode编码是很自然的。 It does not recognize already JSON-like data passed as a string. 它无法识别已经作为字符串传递的类似于JSON的数据。

If you want to get an object, you have to pass an associative array to json_encode : 如果要获取对象,则必须将关联数组传递给json_encode

$foo = array(
    1 => 4,
    7 => 11,
    15 => 11
);

echo json_encode($foo); // {1:4,7:11,15:11}

With so little info about what $wage looks like before it's imploded, it's hard to tell exactly what you want to get. $wage崩溃之前,关于$wage信息很少,因此很难确切地说出您想要得到什么。 How is that structure ( [1,4],[7,11],[15,11] ) an object? 该结构( [1,4],[7,11],[15,11] )如何成为对象? Is the first element of each tuple a key? 每个元组的第一个元素是键吗? That's what I assumed with my example, but it might be off. 这就是我在示例中所假设的,但是可能不正确。

a. 一种。 You get a syntax error because you need to enclose the string within quotes, like so: 您会收到语法错误,因为您需要将字符串用引号引起来,如下所示:

var age = JSON.parse("<?php echo $ww; ?>");

b. Moreover, you don't need JSON.parse . 而且,您不需要 JSON.parse You can simply echo the php var after it was already json_encoded in the server side: 您可以在服务器端对php var进行json_encoded后,直接对其进行回显:

var age = <?php echo $ww; ?>;

JSON.parse is there to convert a JavaScript string to an object. JSON.parse可以将JavaScript字符串转换为对象。 In the case of PHP string, once it is built as JSON, echoing it in the right place is equivalent to coding it yourself. 对于PHP字符串,一旦将其构建为JSON,则在正确的位置回显等同于自己进行编码。

var age = [<?php echo $age; ?>];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM