我有一个 php 对象..我使用 json_encode() 将其转换为 json 文本
功能。然后我将它传递给 javascript 上的 $.parseJSON() 函数。
注意:json 对象中的描述字段包含以 html 实体编码的文本。
在执行 $.parseJSON() 函数时说...
SyntaxError: JSON.parse: bad control character in string literal at line 1 column 133 of the JSON data
但是,如果描述字段只是像 "description":"hy" 这样的普通文本,那么在解析 $.parseJSON() 函数时就没有问题。
需要的是我必须用我在数据库中的 html 实体存储描述字段..
帮帮我...
$(window).load(function editPage(){
var page_data = $.parseJSON('{"id":"1","title":"FAQ","summary":"Frequently Asked Questions are available here","description":"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<\/head>\r\n<body>\r\n<h6 class="section-heading__heading heading--1">What does Shopify do?<\/h6>\r\n<p>&nbsp;<\/p>\r\n<div class="grid-item grid-6 grid-push-1">\r\n<div class="long-form-content ">\r\n<p>Shopify is a complete <code><a class="body-link" href="https:\/\/www.shopify.com\/" target="_blank" rel="noopener">ecommrce solution<\/a><\/code> that allows you to set up an online store to sell your goods. It lets you organize your products, customize your storefront, accept credit card payments, track and respond to orders &mdash; all with a few clicks of the mouse.<\/p>\r\n<\/div>\r\n<\/div>\r\n<\/body>\r\n<\/html>","status":"1","featured_image":"Page-1519912947103.jpg","added_date":"2018-03-01 19:46:28","updated_date":"2018-03-02 10:13:11"}');
console.log(page_data);
}
);
最佳答案
这是因为JSON.parse无法解析一些特殊字符,如\n,\t,\r,\f,需要在解析前替换掉。
$(window).load(function editPage(){
var jsonString='{"id":"1","title":"FAQ","summary":"Frequently Asked Questions are available here","description":"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<\/head>\r\n<body>\r\n<h6 class="section-heading__heading heading--1">What does Shopify do?<\/h6>\r\n<p>&nbsp;<\/p>\r\n<div class="grid-item grid-6 grid-push-1">\r\n<div class="long-form-content ">\r\n<p>Shopify is a complete <code><a class="body-link" href="https:\/\/www.shopify.com\/" target="_blank" rel="noopener">ecommrce solution<\/a><\/code> that allows you to set up an online store to sell your goods. It lets you organize your products, customize your storefront, accept credit card payments, track and respond to orders &mdash; all with a few clicks of the mouse.<\/p>\r\n<\/div>\r\n<\/div>\r\n<\/body>\r\n<\/html>","status":"1","featured_image":"Page-1519912947103.jpg","added_date":"2018-03-01 19:46:28","updated_date":"2018-03-02 10:13:11"}';
jsonString=jsonString.replace(/\n/g, "\\n")
.replace(/\r/g, "\\r")
.replace(/\t/g, "\\t")
.replace(/\f/g, "\\f");
var page_data = $.parseJSON(jsonString);
console.log(page_data);
}
);
关于javascript - 在javascript中解析包含html实体的json编码对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49063145/