How to Remove Carriage Returns from the Json Output of My Webapi Service

How to replace return carriage in json string made from mysql and php?

You will need to escape twice

str_replace("\\r", "", $my_array);

API returns json containing linebreaks etc. how can i clean my json?

You can replace all line breaks by using the following snippet

string content = json.Replace("\n", "");

Environment.NewLine doesn't work here. There is a formatted content below

"publisher": "Pearson",
"language": "Eng",
"image": "https:\/\/\/covers\/34\/13\/9780134093413.jpg",
"title_long": "Campbell Biology (11th Edition)",
"edition": "11",
"pages": 1488,
"date_published": "2017",
"subjects": ["Biology"],
"authors": ["Lisa A. Urry", "Michael L. Cain", "Steven A. Wasserman", "Peter V. Minorsky", "Jane B. Reece"],
"title": "Campbell Biology (11th Edition)",
"isbn13": "9780134093413",
"msrp": "259.99",
"binding": "Hardcover",
"publish_date": "2017",
"isbn": "0134093410"

Then copy the updated string and use Edit-Paste Special-Paste JSON as classes. There is generated classes

public class BookResponse
public Book book { get; set; }

public class Book
public string publisher { get; set; }
public string language { get; set; }
public string image { get; set; }
public string title_long { get; set; }
public string edition { get; set; }
public int pages { get; set; }
public string date_published { get; set; }
public string[] subjects { get; set; }
public string[] authors { get; set; }
public string title { get; set; }
public string isbn13 { get; set; }
public string msrp { get; set; }
public string binding { get; set; }
public string publish_date { get; set; }
public string isbn { get; set; }

Actually, the Book instance is nested in a different class. So, for parsing you have to use something like that

var response = JsonConvert.DeserializeObject<BookResponse>(content);

if ( != null)

Remove carriage return from json text

I tried to use the same library, it seems to have a bug with parsing arrays. That is why I used It has a disadvantage: you need to delete all the objects, unfortunately; as a result there's plenty of code. But at least it works.

Seems your json has incorrect format, I used to cut it a little.

  #include <json1.mqh> //modified version,

//const string post_result=
//"date":1588838583,"text":"A\nGbpusd buy now 1.2360\nSl 1.2280 \nTp open\n","entities":[{"offset":52,"length":11,"type":"mention"}]},"text":"A\n42 pips bookd close\ud83d\udfe2\ud83d\udfe2"}},
//"date":1588893671,"text":"A\nGold buy 1713.3\nSl 1702 \nTp open\nSwing trade"},"text":"Amazon\n60 pips bookd close\ud83d\udfe2\ud83d\udfe2" }}]}

void function()
const string post_result=getContent();//ok, you managed to get some string here

JSONParser *parser=new JSONParser();
JSONValue *value=parser.parse(post_result);
printf("%i %s: error!",__LINE__,__FILE__);
JSONObject *obj=(JSONObject*)value;
const bool isSuccess=obj.getBool("ok");
printf("%i %s: isSuccess=%d",__LINE__,__FILE__,isSuccess);

JSONValue *resultValue=obj.getValue("result");
JSONArray *resultValueArray=resultValue;
for(int i=0;i<resultValueArray.size();i++)
printf("%i %s: #%d=%s",__LINE__,__FILE__,i,resultValueArray.getObject(i).toString());
//you can work with JSONObject or with string, whatever is more convenient
bool parseResultLine(JSONObject *object)
const long update_id=object.getLong("update_id");
JSONObject *channel_post=object.getObject("channel_post");

const long message_id=channel_post.getLong("message_id");
const datetime date=(datetime)channel_post.getInt("date");
const string text=channel_post.getString("text");
printf("%i %s: id=%s, dt=%d/%s, text=%s",__LINE__,__FILE__,IntegerToString(message_id),(int)date,TimeToString(date),text);
JSONObject *chat=channel_post.getObject("chat");
const long chat_id=chat.getLong("id");
const string chat_title=chat.getString("title");
printf("%i %s: chat-> id=%I64d title=%s type=%s",__LINE__,__FILE__,chat_id,chat_title,chat.getString("type"));
JSONObject *reply=channel_post.getObject("reply_to_message");
printf("%i %s: replied: id=%s, date=%s",__LINE__,__FILE__,string(reply.getLong("message_id")),TimeToString(reply.getInt("date")));

return true;

ASP.NET WebAPI: How to control string content returned to client?

This happens because your controller is returning JSON in which string values are quoted.

A simple solution is to parse the responseText as JSON and then you can use the value as intended:

$.ajax("/api/values/10", {
error: function (xhr) {
var error = JSON.parse(xhr.responseText);

This correctly interprets the line breaks/carriage returns.

Alternatively you can specify the text/plain media type in your controller:

return Request.CreateResponse(
"Line1 \r\n Line2", "text/plain");

Web API will then try and load an appropriate media type formatter for text/plain which unfortunately does not exist OOTB. You'll find one in WebApiContrib.

How to explicitly set carriage return when doing json.dump?

If you insist on consistent CRLF behavior (the JSON spec requires parsers to handle both, but opening it in certain plain text readers like Notepad might be easier with consistent CRLF), the solution is in the open function, not the json module.

Just pass newline='\r\n' to open, and it will translate any \n written by json to \r\n seamlessly on all systems, rather than the default behavior of translating to os.linesep (which is \r\n on Windows and \n on most other OSes):

with open(fpath, 'w', encoding="utf-8", newline='\r\n') as outfile:
json.dump(data, outfile, indent=4, sort_keys=True, ensure_ascii=False)

Remove/Replace newline character from JSON in .Net using JsonConvert

You can modify the logic of ReplacingStringConverter from this answer to running a transformation on a Json DeserializeObject for a property to remove \n characters while serializing string value(s).

First, define the following converter:

public class ReplacingStringWritingConverter : JsonConverter
readonly string oldValue;
readonly string newValue;

public ReplacingStringWritingConverter(string oldValue, string newValue)
if (string.IsNullOrEmpty(oldValue))
throw new ArgumentException("string.IsNullOrEmpty(oldValue)");
if (newValue == null)
throw new ArgumentNullException("newValue");
this.oldValue = oldValue;
this.newValue = newValue;

public override bool CanConvert(Type objectType)
return objectType == typeof(string);

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
throw new NotImplementedException();

public override bool CanRead { get { return false; } }

public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
var s = ((string)value).Replace(oldValue, newValue);

Then you can serialize your root data model as follows:

var settings = new JsonSerializerSettings { Converters = { new ReplacingStringWritingConverter("\n", "") } };
var newJson = JsonConvert.SerializeObject(root, Formatting.None, settings);

The converter works when serializing both typed data models with a fixed schema and LINQ to JSON freeform JSON captured in a JToken hierarchy.

(As an aside, I believe your value.Replace() is failing because JSON string values never actually contain newline characters. Instead, as specified by the JSON standard, a newline character must be replaced by the two-character escape sequence \n. Thus value.Replace("\n", string.Empty) fails, as the \n in your code is the c# escape sequence for an actual newline character -- which is not present.)

Demo fiddle here.

Related Topics

Leave a reply