search
Homephp教程php手册php和javascript中Json操作总结

php和javascript中Json操作总结

Jun 06, 2016 pm 07:57 PM
javascriptjsonphpbigSummarizeoperate

阮一峰大牛的博客里提到: 从结构上看,所有的数据(data)最终都可以分解成三种类型: 第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字(numbers),比如北京这个单独的词。 第二种类型是序列(sequence),也就是若干个相关的数据按

阮一峰大牛的博客里提到:

从结构上看,所有的数据(data)最终都可以分解成三种类型:

第一种类型是标量(scalar),也就是一个单独的字符串(string)或数字(numbers),比如"北京"这个单独的词。

第二种类型是序列(sequence),也就是若干个相关的数据按照一定顺序并列在一起,又叫做数组(array)或列表(List),比如"北京,上海"。

第三种类型是映射(mapping),也就是一个名/值对(Name/value),即数据有一个名称,还有一个与之相对应的值,这又称作散列(hash)或字典(dictionary),比如"首都:北京"。

Json的规定:

1) 并列的数据之间用逗号(", ")分隔。

2) 映射用冒号(": ")表示。

3) 并列数据的集合(数组)用方括号("[]")表示。

4) 映射的集合(对象)用大括号("{}")表示。

上面四条规则,就是Json格式的所有内容。

php中JSON的格式:

{"node":1,"left":{"node":2,"left":4,"right":5},"right":3}

如果json块里全是array的话:

[{"city":"\u5929\u6d25","pm25":"58"},{"city":"\u77f3\u5bb6\u5e84","pm25":"42"},{"city":"\u4e0a\u6d77","pm25":"52"}]

json_decode()的常见错误

  $bad_json = "{ 'bar': 'baz' }";

  $bad_json = '{ bar: "baz" }';

  $bad_json = '{ "bar": "baz", }';

对这三个字符串执行json_decode()都将返回null,并且报错。

第一个的错误是,php中 json的分隔符(delimiter)只允许使用双引号,不能使用单引号。第二个的错误是,json名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第三个的错误是,最后一个值之后不能添加逗号(trailing comma

javascript中的JSON:

<script></script>

var a = {name:"tom",sex:"man",age:"24"}; //a 是对象

var b = '{"name":"Mike","sex":"woman","age":"29"}'; //b 是字符串

var a2str = JSON.stringify(a); //对象转成字符串

var b2obj = JSON.parse(b); //字符串转成对象


其实就是一种object;

最简单的,比如: var a = {"name":"Jack"};

这里,name部分的引号不是必须的,而“Jack”的是必须的,如果写成这样 var a = {name:Jack};

就会报错:Uncaught ReferenceError: Jack is not defined 


Statement
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

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools