• Web JSON基础讲解


    技术交流,DH讲解.

    JSON,后XML时代的产物,在XML被大家广泛接受的时候,人们开始注意到XML的冗余数据了,所以有人就在想一些XML的变种,什么BinaryXML之类的,JSON差不多就在这个年代出生了.
    我们先看一个XML

    <request>
      <firstName>Brett</firstName>
      <lastName>McLaughlin</lastName>
      <email>brett@newInstance.com</email>
    </request>
    

    这个XML中,每个标签都出现了2次,用了这么多流量了,何况中国这网络,当然比俄罗斯用铁丝当网线好,哈哈.
    那么对应的JSON会是什么样子的呢?

    { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" }
    

    这样标签只出现了一次,节约了点儿空间,名称:值,成对出现.来个复杂点儿的例子:

    { "people": [
      { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
      { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
      { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
    ]}
    

    一个标签下面有多个标签的时候用[]来括起来.有点儿基础的朋友看了这个介绍应该都会了,我也不继续往下面说了,也没有什么好说的了.
    接下来看看JS中怎么使用JSON.
    JSON是JS一个内置数据类型,所以不需要什么3方文件就能解析,相比Delphi就汗颜了N多,正则不支持,JSON不支持...哎.
    来个JSON变量,看看怎么定义:

    var people =
      { "programmers": [
        { "firstName": "Brett", "lastName":"McLaughlin", "email": "brett@newInstance.com" },
        { "firstName": "Jason", "lastName":"Hunter", "email": "jason@servlets.com" },
        { "firstName": "Elliotte", "lastName":"Harold", "email": "elharo@macfaq.com" }
       ],
      "authors": [
        { "firstName": "Isaac", "lastName": "Asimov", "genre": "science fiction" },
        { "firstName": "Tad", "lastName": "Williams", "genre": "fantasy" },
        { "firstName": "Frank", "lastName": "Peretti", "genre": "christian fiction" }
       ],
      "musicians": [
        { "firstName": "Eric", "lastName": "Clapton", "instrument": "guitar" },
        { "firstName": "Sergei", "lastName": "Rachmaninoff", "instrument": "piano" }
       ]
      }
    

    如何访问其中的元素呢?其实这个就相当于几个组合数组了,我们用下标来访问:

    people.authors[1].genre			// "fantasy"
    
    people.musicians[3].lastName		// Undefined.没有第四个元素
    
    people.programmers.[2].firstName	// "Elliotte"
    people.musicians[1].lastName = "Rachmaninov"; //修改某个元素的值
    
    

    最后看看JSON元素转换字符串:

    String newJSONtext = people.toJSONString();
    

    注意在JS中,任何Obj都有toJSONString()方法,都能转换成JSON形式的字符串.

    Delphi中如何解析JSON,有空写个文章,或者大家去万一博客看看(http://del.cnblogs.com).

    好的,我是DH.今天就这么点儿废话.

  • 相关阅读:
    cookie操作和代理
    发起post请求
    scrapy核心组件
    爬取多个url页面数据--手动实现
    scrapy之持久化存储
    selenium + phantomJs
    scrapy框架简介和基础使用
    校验验证码 实现登录验证
    beautifulsoup解析
    xpath
  • 原文地址:https://www.cnblogs.com/huangjacky/p/1639175.html
Copyright © 2020-2023  润新知