Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to encode JSON embedded within JSON

Tags:

json

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?

like image 656
Johann Avatar asked Oct 13 '11 06:10

Johann


People also ask

How do you encode a data in JSON?

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.

Can you have a JSON in a JSON?

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.

What is encode in JSON?

The json_encode() function is used to encode a value to JSON format.

Can you JSON encode a string?

The answer is yes: JSON.


1 Answers

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="
}
like image 69
Oli Avatar answered Sep 21 '22 13:09

Oli