2017-02-15 78 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