json文件中的换行问题

时间:2018-06-22 09:58:17

标签: javascript json

我从系统中导出数据并获取此内容块,如何删除换行符,使它们全都是一行。

我尝试了诸如“ jsonData.replace(/[\r\n]+/g, '\n\n');”之类的各种操作,但似乎无济于事。

{"pageUrl":"/about","name":"About Us","content":"\n    \n        \n        
\n    
About
\n        
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\n        
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\n    \n"}

这是完整的代码,上面只是json文件中的一项

function list_pages(){
    var access_token = BCAPI.Helper.Site.getAccessToken();
    var request = $.ajax({
        url: "/webresources/api/v3/sites/current/pages?fields=pageUrl,name,content",
        type: "GET",
        connection: "keep-alive",
        contentType: "application/json",
        headers: {
            "Authorization": $.cookie('access_token')
        }
    });
    request.done(function (msg) {
        var myJSONString = JSON.stringify(msg.items);
        **var myEscapedJSONString = myJSONString.replace(/[\r\n]/g, '');**
        $( "#results" ).append( myEscapedJSONString );
    })
    request.fail(function (jqXHR) {
        console.log("Request failed.");
        console.log("Error code: " + jqXHR.status);
        console.log("Error text: " + jqXHR.statusText);
        console.log("Response text: " + jqXHR.responseText);
    })
   }

1 个答案:

答案 0 :(得分:3)

更新后的答案

您对问题的编辑会完全更改它。您正在对replace的结果进行JSON.stringify,这将从不生成您在问题中使用的JSON(实际的回车符和/或换行符字符串)。

在一条评论中,您说过您的目标是查看格式化的JSON数据。为此:

  • 通过向通话中添加JSON.stringify来告诉null, n对其进行格式化,其中n是您希望事物缩进多少。例如:JSON.stringify(msg.items, null, 4)
  • &替换为&amp;,将<替换为&lt;(按此顺序)。
  • 输出到具有white-space CSS设置的pre设置之一的元素(例如,一个pre元素,但您也可以使用CSS做到这一点)

所以:

var htmlToDisplay = jsonData
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;");

...然后将其放在带有white-space: pre的元素中。

示例:

var msg = {
  items: [
    {
      pageUrl: "/about",
      name: "About Us",
      content: "\n    \n        \n        \n    About\n        Lorem ipsum dolor sit amet, consectetur adipisicing elit..."
    }
  ]
};
var jsonData = JSON.stringify(msg.items, null, 4);
var htmlToDisplay = jsonData
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;");
$("#results").append(htmlToDisplay);
#results {
  white-space: pre;
  font-family: monospace;
}
<div id="results"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

您可以尝试设置white-space的其他设置,例如pre-wrap

var msg = {
  items: [
    {
      pageUrl: "/about",
      name: "About Us",
      content: "\n    \n        \n        \n    About\n        Lorem ipsum dolor sit amet, consectetur adipisicing elit..."
    }
  ]
};
var jsonData = JSON.stringify(msg.items, null, 4);
var htmlToDisplay = jsonData
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;");
$("#results").append(htmlToDisplay);
#results {
  white-space: pre-wrap;
  font-family: monospace;
}
<div id="results"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


原始答案

您不想用换行符替换那些无效的换行符;您想一无所有地替换它们:

jsonData = jsonData.replace(/[\r\n]/g, '');

let jsonData = document.getElementById("the-json").textContent;
jsonData = jsonData.replace(/[\r\n]/g, '');
console.log(JSON.parse(jsonData));
<script id="the-json" type="text/json">{"pageUrl":"/about","name":"About Us","content":"\n    \n        \n        
\n    
About
\n        
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\n        
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod 
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, 
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo 
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse 
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non 
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
\n    \n"}</script>