0

I have a curl statement that pulls json formatted array to php. I then want to transfer this array to jQuery so that the client side will hold the array. I'm currently using the below method:

<script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script> 

The client sees something like:

<script>var obj = jQuery.parseJSON( array(1) { ["search"]=> array(50) { [0]=> array(6) { ["id"]=> string(6) "641279" ["description"]=> string(36) "Instyle - Responsive Portfolio Theme" ["url"]=> string(69) "http://themeforest.net/item/instyle-responsive-portfolio-theme/641279" ["type"]=> string(9) "wordpress" ["sales"]=> string(3) "135" ["rating"]=> string(3) "4.5" } .... } } );</script> 

Will obj now hold the array? is this the right way becuase I'm getting an error:

Uncaught SyntaxError: Unexpected token { 
2
  • JSON.parse() expect parameter to be a string. Commented Feb 6, 2014 at 15:11
  • Although your question is a lil confusing, i believe you should use print_r instead of var_dump Commented Feb 6, 2014 at 15:14

5 Answers 5

2

PHP has json_encode function already, you should use that.

Would look like:

<script> var a = <?php echo json_encode($json_short); ?>; </script> 
Sign up to request clarification or add additional context in comments.

2 Comments

You would need quotes around this for it to store as a string.
That is true, but he does not want to have a string. He wants a native object or array, hence the proposed use of parseJSON() in order to convert from string to usable object.
1

You cannot use a direct dump, you need to json_encode first:

<script>var obj = <?php echo json_encode($json_short) ?>;</script>

Comments

0

I don't understand what you're trying with <script>var obj = jQuery.parseJSON( <?php echo var_dump($json_short); ?> );</script>

in PHP try echo json_encode($json_short);

Comments

0

the var_dump function doesn't dump it as a json object.

use json_encode instead of var_dump.

Comments

-1

Don't use var_dump first off. Next make sure you have converted your variable to a json array you have a normal array.

<script>var obj = jQuery.parseJSON( <?php echo json_encode($json_short); ?> );</script> 

4 Comments

he shouldn't even need to use parseJSON. That takes a string and turns it into an array or obj or whatever. If json_encode is used, the data is immediately usable in javascript.
Only if he wants to use it as a string if he actually wants to be able to access the data like obj.search[0].id then he would need to parse it.
Also if he just wants to store it as a string then ' or " would need to go around it.
He would have to parseJSON if he has a string. Using json_encode allows him to skip that step since it will be placed in javascript as a usable object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.