Home php教程 PHP视频 How to handle special characters in JSON

How to handle special characters in JSON

Dec 03, 2016 pm 01:29 PM
json

JSON 是适用于 Ajax 应用程序的一种有效格式,原因是它使 JavaScript 对象和字符串值之间得以快速转换。由于 Ajax 应用程序非常适合将纯文本发送给服务器端程序并对应地接收纯文本,相比不能生成文本的 API,能生成文本的 API 自然更可取;而且,JSON 让您能够处理本地 JavaScript 对象,而无需为如何表示这些对象多费心思。

XML 也可以提供文本方面的类似益处,但用于将 JavaScript 对象转换成 XML 的几个现有 API 没有 JSON API 成熟;有时,您必须在创建和处理 JavaScript 对象时格外谨慎以确保所进行的处理能与所选用的 XML 会话 API 协作。但对于 JSON,情况就大不相同:它能处理几乎所有可能的对象类型,并会返回给您一个非常好的 JSON 数据表示。 因此,JSON 的最大价值在于可以将 JavaScript 真的作为 JavaScript 而非数据格式语言进行处理。

您所学到的所有有关使用 JavaScript 对象的技巧都可以应用到代码中,而无需为如何将这些对象转变成文本而多费心思。

1. 回车问题

JSON传值的时候,如果有回车符就会挂的。我们可以使用正则来去掉回车符:

$str = preg_replace("'([\r\n])[\s]+'", "", $str);
 
 // 不用正则
 
 $str = str_replace("\n","",$str);
Copy after login

转出来的字符串就没有回车符的困扰了。

顺便记录一个PHP过滤脚本:

<?php
 
 // $document 应包含一个 HTML 文档。
 
// 本例将去掉 HTML 标记,javascript 代码
 
// 和空白字符。还会将一些通用的
 
 // HTML 实体转换成相应的文本。
 
 $search = array ("&#39;<script[^>]*?>.*?</script>&#39;si", // 去掉 javascript
 
         "&#39;<[\/\!]*?[^<>]*?>&#39;si",      // 去掉 HTML 标记
 
         "&#39;([\r\n])[\s]+&#39;",         // 去掉空白字符
 
         "&#39;&(quot|#34);&#39;i",         // 替换 HTML 实体
 
         "&#39;&(amp|#38);&#39;i",
 
         "&#39;&(lt|#60);&#39;i",
 
         "&#39;&(gt|#62);&#39;i",
 
         "&#39;&(nbsp|#160);&#39;i",
 
         "&#39;&(iexcl|#161);&#39;i",
 
         "&#39;&(cent|#162);&#39;i",
 
         "&#39;&(pound|#163);&#39;i",
 
         "&#39;&(copy|#169);&#39;i",
 
         "&#39;&#(\d+);&#39;e");          // 作为 PHP 代码运行
 
 $replace = array ("",
 
          "",
 
          "\\1",
 
 
          "\"",
          "&",
 
          "<",
 
          ">",
 
          " ",
 
         chr(161),
 
          chr(162),
 
          chr(163),
 
         chr(169),
 
          "chr(\\1)");
 
 $text = preg_replace ($search, $replace, $document);
 
 ?>
Copy after login

2. HTML特殊字符

从服务器端以JSON格式将数据传递到客户端后,通过JS显示在HTML页面时,有一些特殊字符不能直接显示,如后台传递过来的是 'msg #' 通过JS显示在HTML页面中时,显示成了 msg # ,并不是msg #,这是由于<与>之间的内容看作是HTML标签了,而以&开头的 与#为HTML实体,所以显示不正常。

解决办法很简单,在JS将其渲染到HTML页面前转换一下即可:

<script type="text/javascript"> 
 
 var str = &#39;<b>msg</b> #&#39;; 
 
 document.all.div1.innerHTML=&#39;<pre class="brush:php;toolbar:false">&#39;+str+&#39;
'; //js中的字符串正常显示在HTML页面中 String.prototype.displayHtml= function(){ //将字符串转换成数组 var strArr = this.split(''); //HTML页面特殊字符显示,空格本质不是,但多个空格时浏览器默认只显示一个,所以替换 var htmlChar="&<>"; for(var i = 0; i< str.length;i++){ //查找是否含有特殊的HTML字符 if(htmlChar.indexOf(str.charAt(i)) !=-1){ //如果存在,则将它们转换成对应的HTML实体 switch (str.charAt(i)) { case '<': strArr.splice(i,1,'<'); break; case '>': strArr.splice(i,1,'>'); break; case '&': strArr.splice(i,1,'&'); } } } return strArr.join(''); } alert(str.displayHtml()); document.all.div2.innerHTML=str.displayHtml();
Copy after login

3. escape()函数

该函数可以处理空格、斜线和其他任何可能影响浏览器的内容,并将它们转换成 Web 可用字符(比如,空格会被转换成 %20,浏览器并不会将其视为空格处理,而是不做更改,将其直接传递到服务器)。之后,服务器会(通常自动)再把它们转换回它们传输后的本来 “面目”。

var url = "nowamagic.php?people=" + escape(people.toJSONString());
 
 request.open("GET", url, true);
 
request.onreadystatechange = updatePage;
 
request.send(null);
Copy after login

这种做法的缺点有两个: 在使用 GET 请求发送大块数据时,对 URL 字符串有长度限制。虽然这个限制很宽泛,但对象的 JSON 字符串表示的长度可能超出您的想象,尤其是在使用极其复杂的对象时更是如此。在跨网络以纯文本发送所有数据的时候,发送数据面临的不安全性超出了您的处理能力。

简言之,以上是 GET 请求的两个限制,而不是简单的两个与 JSON 数据相关的事情。在想要发送用户名和姓之外的更多内容,比如表单中的选择时,二者可能会需要多加注意。若要处理任何机密或极长的内容,可以使用 POST 请求。

4. 引号问题

JSON中如果包含引号或双引号,会破坏JSON的格式。有两种方法可以解决。

在入库的时候可以使用addslashes()函数处理一下字符串,给引号前加上斜杠。被改的字符包括单引号 (')、双引号 (")、反斜线 backslash (\) 以及空字符NULL。

$text = addslashes($text);
 
JavaScript的话,可以这样:
 
 function valueReplace(v){
 
 v=v.toString().replace(new RegExp(&#39;(["\"])&#39;, &#39;g&#39;),"\\\"");
 
return v;
 
 }
 
 var eValue = encodeURI($.trim(valueReplace(e.value)))
Copy after login

   


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1655
14
PHP Tutorial
1254
29
C# Tutorial
1228
24
Combination of golang WebSocket and JSON: realizing data transmission and parsing Combination of golang WebSocket and JSON: realizing data transmission and parsing Dec 17, 2023 pm 03:06 PM

The combination of golangWebSocket and JSON: realizing data transmission and parsing In modern Web development, real-time data transmission is becoming more and more important. WebSocket is a protocol used to achieve two-way communication. Unlike the traditional HTTP request-response model, WebSocket allows the server to actively push data to the client. JSON (JavaScriptObjectNotation) is a lightweight format for data exchange that is concise and easy to read.

How to exclude a field from JSON using @Expose annotation in Java? How to exclude a field from JSON using @Expose annotation in Java? Sep 16, 2023 pm 09:49 PM

The Gson@Expose annotation can be used to mark whether a field is exposed (contained or not) for serialization or deserialization. The @Expose annotation can take two parameters, each parameter is a boolean value and can take the value true or false. In order for GSON to react to the @Expose annotation, we have to create a Gson instance using the GsonBuilder class and need to call the excludeFieldsWithoutExposeAnnotation() method, which configures Gson to exclude all fields without Expose annotation from serialization or deserialization. Syntax publicGsonBuilderexclud

Performance optimization tips for converting PHP arrays to JSON Performance optimization tips for converting PHP arrays to JSON May 04, 2024 pm 06:15 PM

Performance optimization methods for converting PHP arrays to JSON include: using JSON extensions and the json_encode() function; adding the JSON_UNESCAPED_UNICODE option to avoid character escaping; using buffers to improve loop encoding performance; caching JSON encoding results; and considering using a third-party JSON encoding library.

What is the difference between MySQL5.7 and MySQL8.0? What is the difference between MySQL5.7 and MySQL8.0? Feb 19, 2024 am 11:21 AM

MySQL5.7 and MySQL8.0 are two different MySQL database versions. There are some main differences between them: Performance improvements: MySQL8.0 has some performance improvements compared to MySQL5.7. These include better query optimizers, more efficient query execution plan generation, better indexing algorithms and parallel queries, etc. These improvements can improve query performance and overall system performance. JSON support: MySQL 8.0 introduces native support for JSON data type, including storage, query and indexing of JSON data. This makes processing and manipulating JSON data in MySQL more convenient and efficient. Transaction features: MySQL8.0 introduces some new transaction features, such as atomic

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string Nov 18, 2023 pm 01:59 PM

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string. When writing programs in Golang, we often need to convert the structure into a JSON string. In this process, the json.MarshalIndent function can help us. Implement formatted output. Below we will explain in detail how to use this function and provide specific code examples. First, let's create a structure containing some data. The following is an indication

How to handle XML and JSON data formats in C# development How to handle XML and JSON data formats in C# development Oct 09, 2023 pm 06:15 PM

How to handle XML and JSON data formats in C# development requires specific code examples. In modern software development, XML and JSON are two widely used data formats. XML (Extensible Markup Language) is a markup language used to store and transmit data, while JSON (JavaScript Object Notation) is a lightweight data exchange format. In C# development, we often need to process and operate XML and JSON data. This article will focus on how to use C# to process these two data formats, and attach

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

Annotations in the Jackson library control JSON serialization and deserialization: Serialization: @JsonIgnore: Ignore the property @JsonProperty: Specify the name @JsonGetter: Use the get method @JsonSetter: Use the set method Deserialization: @JsonIgnoreProperties: Ignore the property @ JsonProperty: Specify name @JsonCreator: Use constructor @JsonDeserialize: Custom logic

Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Use PHP's json_encode() function to convert an array or object into a JSON string and format the output Nov 03, 2023 pm 03:44 PM

Using PHP's json_encode() function to convert an array or object into a JSON string and format the output can make it easier to transfer and exchange data between different platforms and languages. This article will introduce the basic usage of the json_encode() function and how to format and output a JSON string. 1. Basic usage of json_encode() function The basic syntax of json_encode() function is as follows: stringjson_encod

See all articles