How do I convert an escaped JSON string within a JSON object?
Here's the workable solution I used based off of Sam I am's answer:
dynamic obj = JsonConvert.DeserializeObject(json);
foreach (var response in (IEnumerable<dynamic>)obj.responses)
{
response.body = JsonConvert.DeserializeObject((string)response.body);
}
string result = JsonConvert.SerializeObject(obj);
How to escape a JSON string containing newline characters using JavaScript?
Take your JSON and .stringify()
it. Then use the .replace()
method and replace all occurrences of \n
with \\n
.
EDIT:
As far as I know of, there are no well-known JS libraries for escaping all special characters in a string. But, you could chain the .replace()
method and replace all of the special characters like this:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// myEscapedJSONString is now ready to be POST'ed to the server.
But that's pretty nasty, isn't it? Enter the beauty of functions, in that they allow you to break code into pieces and keep the main flow of your script clean, and free of 8 chained .replace()
calls. So let's put that functionality into a function called, escapeSpecialChars()
. Let's go ahead and attach it to the prototype chain
of the String
object, so we can call escapeSpecialChars()
directly on String objects.
Like so:
String.prototype.escapeSpecialChars = function() {
return this.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
};
Once we have defined that function, the main body of our code is as simple as this:
var myJSONString = JSON.stringify(myJSON);
var myEscapedJSONString = myJSONString.escapeSpecialChars();
// myEscapedJSONString is now ready to be POST'ed to the server
How to escape special characters in building a JSON string?
A JSON string must be double-quoted, according to the specs, so you don't need to escape '
.
If you have to use special character in your JSON string, you can escape it using \
character.
See this list of special character used in JSON :
\b Backspace (ascii code 08)
\f Form feed (ascii code 0C)
\n New line
\r Carriage return
\t Tab
\" Double quote
\\ Backslash character
However, even if it is totally contrary to the spec, the author could use \'
.
This is bad because :
- It IS contrary to the specs
- It is no-longer JSON valid string
But it works, as you want it or not.
For new readers, always use a double quotes for your json strings.
Java escape JSON String?
I would use a library to create your JSON String
for you. Some options are:
- GSON
- Crockford's lib
This will make dealing with escaping much easier. An example (using org.json
) would be:
JSONObject obj = new JSONObject();
obj.put("id", userID);
obj.put("type", methoden);
obj.put("msg", msget);
// etc.
final String json = obj.toString(); // <-- JSON string
How to convert escaped json into a struct
Some might do a custom unmarshal method, but I think it's easier just to do two passes:
package main
import (
"encoding/json"
"fmt"
)
const s = `
{
"key": "123",
"sources": "{\"1a\":\"source1a\",\"2b\":\"source2b\",\"3c\":\"source3c\",\"default\":\"sourcex\"}"
}
`
func main() {
var t struct{Key, Sources string}
json.Unmarshal([]byte(s), &t)
m := make(map[string]string)
json.Unmarshal([]byte(t.Sources), &m)
fmt.Println(m) // map[1a:source1a 2b:source2b 3c:source3c default:sourcex]
}
How to fix an escaped JSON string (JavaScript)
Assuming that is the actual value shown then consider:
twice_json = '"{\\"orderId\\":\\"123\\"}"' // (ingore the extra slashes)
json = JSON.parse(twice_json) // => '{"orderId":"123"}'
obj = JSON.parse(json) // => {orderId: "123"}
obj.orderId // => "123"
Note how applying JSON.stringify to the json
value (which is a string, as JSON is text) would result in the twice_json
value. Further consider the relation between obj
(a JavaScript object) and json
(the JSON string).
That is, if the result shown in the post is the output from JSON.stringify(res)
then res is already JSON (which is text / a string) and not a JavaScript object - so don't call stringify on an already-JSON value! Rather, use obj = JSON.parse(res); obj.orderId
, as per the above demonstrations/transformations.
How do I deserialize a property containing an escaped JSON string?
You could use a custom JsonConverter for this similar to this:
public class EmbeddedJsonConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
return serializer.Deserialize(new StringReader((string)reader.Value), objectType);
}
public override bool CanConvert(Type objectType)
{
return true;
}
}
Mark the property with [JsonConverter(typeof(EmbeddedJsonConverter))]
like:
public class Response
{
public DateTime time { get; set; }
public string event_name { get; set; }
public string event_type { get; set; }
public string method { get; set; }
[JsonConverter(typeof(EmbeddedJsonConverter))]
public MessageDetails message_details { get; set; }
}
Then you will be able to deserialize with JsonConvert.DeserializeObject<Response>()
.
The EmbeddedJsonConverter class extracts the json string from the object and then deserializes it. CanConvert
should probably be made smarter for a truly generic use.
Parse escaped json string in Golang
Wrap your incoming string before unquoting it like this:
s,err := strconv.Unquote(`"`+yourstring+`"`)
Then you can proceed with unmarshalling it.
Related Topics
Difference Between Parameters.Add(String, Object) and Parameters.Addwithvalue
Access to the Path Is Denied When Using Directory.Getfiles(...)
Searching for File in Directories Recursively
How to Mock Non Virtual Methods
Returning Only Part of Match from Regular Expression
Windows Forms Splash Screen - Show a Form While Loading Main Form
Windows Phone 8.1 Universal App Terminates on Navigating Back from Second Page
External JSON Vulnerable Because of JSON.Net Typenamehandling Auto
How Does JSON Deserialization in C# Work
Xml-Selectnodes with Default-Namespace via Xmlnamespacemanager Not Working as Expected
Calling Async Methods from a Wcf Service
Prevent Using Dispatcher.Invoke in Wpf Code
Multiple Parallel.Foreach Loops in .Net