I have a JSON string and one of the fields is a text field. This text field can contain text that a user enters in the UI and if the text they enter is JSON text, perhaps to illustrate some coding, I need to encode their text so that it does not get interpreted as JSON within the actual JSON structure sent to the server.
When the JSON structure is received by the server and gets decoded, I need to make sure the embedded JSON gets decoded as text, which ends up looking like JSON in the UI.
In effect, how do you escape an embedded JSON string?
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode() , respectively. Both functions only works with UTF-8 encoded string data.
JSON can actually take the form of any data type that is valid for inclusion inside JSON, not just arrays or objects. So for example, a single string or number would be valid JSON.
The json_encode() function is used to encode a value to JSON format.
The answer is yes: JSON.
I'm doing something similar, just with XML instead of JSON: On receiving malformed or otherwise non-processable data the server returns an error-structure containing some information and the original data. To prevent the client from parsing the corrupt data again it's base64 encoded on the server.
So instead of sending
{
title : "My sample code",
payload : "{ \"foo\" : \"bar\" }"
}
consider sending
{
title : "My encoded sample code",
payload : "eyAiZm9vIiA6ICJiYXIiIH0="
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With