2017-02-15 88 views
0

我試圖發送一些Markdown文本到休息api。剛纔我發現在json中不接受斷行。如何發送MarkDown到API

例子。如何將這個發到我的API:

An h1 header 
============ 

Paragraphs are separated by a blank line. 

2nd paragraph. *Italic*, **bold**, and `monospace`. Itemized lists 
look like: 

    * this one 
    * that one 
    * the other one 

Note that --- not considering the asterisk --- the actual text 
content starts at 4-columns in. 

> Block quotes are 
> written like so. 
> 
> They can span multiple paragraphs, 
> if you like. 

Use 3 dashes for an em-dash. Use 2 dashes for ranges (ex., "it's all 
in chapters 12--14"). Three dots ... will be converted to an ellipsis. 
Unicode is supported. ☺ 

{ 
    "body" : " (the markdown) ", 
} 
+1

在將其添加到JSON對象之前,您需要「轉義」您的Markdown文本。由於您沒有告訴我們您正在使用哪種語言/框架,因此以下是「 [escape json](http://stackoverflow.com/search?q=escape+json)「。 – Waylan

+1

將Markdown放入字符串或類似字符串的對象中。將該字符串放入適當的數據結構中。使用你的語言的數據到JSON函數。 (提示:** _從來沒有_ **手動構建JSON。) – Chris

+0

謝謝你們,這是一個普遍的問題,但我明白了。謝謝 – 62009030

回答

1

當你試圖將它發送到一個REST API終點,我會假設你正在尋找方法來做到這一點使用Javascript(因爲你沒有指定你使用的是什麼技術)。

經驗法則:除非您的目標是重新構建JSON構建器,否則使用已有的構建器。

而且,猜猜看,Javascript實現了它的JSON工具! (see documentation here

如在the documentation中所示,您可以使用JSON.stringify函數簡單地將對象(如字符串)轉換爲json兼容的編碼字符串,稍後可以在服務器端對其進行解碼。

這個例子說明如何做到這一點:

var arr = { 
    text: "This is some text" 
}; 
var json_string = JSON.stringify(arr); 
// Result is: 
// "{"text":"This is some text"}" 
// Now the json_string contains a json-compliant encoded string. 

也可以使用其他的方法JSON.parse()see documentation)解碼JSON的客戶端使用javascript:

var json_string = '{"text":"This is some text"}'; 
var arr = JSON.parse(json_string); 
// Now the arr contains an array containing the value 
// "This is some text" accessible with the key "text" 

如果還是不行回答你的問題,請編輯它以使其更加精確,尤其是你使用的是什麼技術。我將相應地編輯此答案

+0

謝謝!而已 – 62009030