1

I have a huge list of things with each of those things broken down into four sub-things. I am easily able to gather them in nested arrays in PHP, but when I use json_encode to pass them as a JSON object to my javascript client side, the JSON.parse() function always fails because my data is filled with all kinds of entities like ' / \ " & % {} []

It's a shame there is no constant that you can add to json_encode to ensure it's javascript ready.

What characters must I escape or otherwise deal with to ensure I get a javascript parsable object. I was unable to find one. I could easily write a function to handle this if I knew which characters to deal with.

1 Answer 1

1

There should be no problem with your approach. Maybe there is a problem when rendering the data? Did you try the following to output the json?

echo 'var myjs = ' . htmlspecialchars(json_encode($obj)) . ';';

If you render the json in a different url/endpoint you do not have to encode anything yourself. However you should make sure your http headers are set correctly

header('Content-Type: application/json');
echo json_encode($obj);
die(0); # thx for requesting my endpoint
Sign up to request clarification or add additional context in comments.

2 Comments

I was just passing the nested array as json_encode($array). I will try the htmlspecialcharacters approach. And I like the idea of grabbing the object after page load, I may just do that. It may end up that way anyways. Thanks!
htmlspecialcharacters didn't work. I just passed it directly as a var as you said without using JSON.parse, and it all worked fine. In the end I built a small php function to create a javascript array of objects and pushed it into the javascript var and it all works great, no worry about special characters at all.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.