JSON data structure

Source: Internet
Author: User
Tags string back tag name

JSON, or JavaScript Object natation, is a lightweight data interchange format that is ideal for server-to-javascript interaction. JSON is easy for people to read and write. It is also easy for machine parsing and generation. JSON uses a completely separate language text format, but it also uses a language similar to the C family (including C,c++,c#,java,javascript,perl,python, etc.). These features make JSON an ideal data exchange language.

XML is also a data interchange format, but the XML tag is more, often making the tag more than the data that needs to be passed, which increases the burden of character transmission.

JSON is constructed in two structures:

1. Collection of "name/value" pairs (A collection of Name/value Pairs). In different languages, it is understood as objects (object), record (record), structure (struct), Dictionary (dictionary), hash table (hash table), List of keys (keyed lists), or an associative array (associative array).

2. Ordered list of values (an ordered list of values). In most languages, it is understood as an array (array).

Python's JSON module provides a very simple way to encode and decode JSON data. Two of the main functions are json.dumps () and Json.loads (), which is much less than the interfaces of other serialization function libraries such as pickle. The following shows how to convert a Python data structure to JSON:

import json data  = { ‘name‘ ‘ACME‘ , ‘shares‘ 100 , ‘price‘ 542.23 } json_str  = json.dumps(data)The following shows how to convert a JSON-encoded string back to a python data structure: data = json.loads (JSON_STR) If you are dealing with files instead of strings, you can use Json.dump () and Json.load () To encode and decode JSON data. For example: # Writing JSON data with  open ( ‘data.json‘ ‘w‘ ) as f:   json.dump(data, f) # Reading data back with  open ( ‘data.json‘ ‘r‘ ) as f:   data  = json.load(f)Json.dumps and Json.loads instances

The following example demonstrates the conversion of a PYTHON data structure to JSON:

#!/usr/bin/python3import json# Python dictionary type converted to JSON object data = {    ' no ': 1,    ' name ': ' W3cschool ',    ' url ': ' http ://www.w3cschool.cn '}json_str = json.dumps (data) print ("Python raw Data:", repr (data)) print ("JSON object:", Json_str)

Execute the above code to output the result:

Python raw data: {' URL ': ' http://www.w3cschool.cn ', ' No ': 1, ' name ': ' W3cschool '}json object: {' URL ': ' http://www.w3cschool.cn ', "No": 1, "name": "W3cschool"}

The result of the output shows that the simple type is very similar by encoding followed by its original repr () output.

Next, we can convert a JSON-encoded string back to a python data structure:

#!/usr/bin/python3import json# Python dictionary type converted to JSON object data1 = {    ' no ': 1,    ' name ': ' W3cschool ',    ' url ': ' http:/ /www.w3cschool.cn '}json_str = Json.dumps (data1) print ("Python raw Data:", repr (data1)) print ("JSON object:", JSON_STR) # will JSON object Convert to Python dictionary data2 = json.loads (json_str) print ("data2[' name ']:", data2[' name ']) print ("data2[' url ']:", data2[' url '))

Execute the above code to output the result:

Ython raw data: {' name ': ' W3cschool ', ' No ': 1, ' url ': ' http://www.w3cschool.cn '}json object: {' name ': ' W3cschool ', ' No ': 1, ' URL ': "http://www.w3cschool.cn"}data2[' name ':  w3cschooldata2[' url ']:  http://www.w3cschool.cn

If you are dealing with files instead of strings, you can use json.dump () and json.load () to encode and decode JSON data. For example:

# Write JSON data with open (' Data.json ', ' W ') as F:    json.dump (data, f) # Read data with open (' Data.json ', ' R ') as F:    data = JSO N.load (f)
There are two main types of data interchange formats: XML, JSON3 IOS Development Common parsing: 3.1 XML parsing: SAX parsing and DOM parsing XML parsing tools: Nsxmlparser, Gdataxmlnode, Touchxml, and KISSXM L et 3.2 JSON parsing and parsing tools: Jsonkit, Nsjsonserialization, Touchjson and Sbjson, Nsjsonserialization (System-provided parsing class, best performance, highest parsing efficiency) two XML data Structures----XML------1 Extensible Markup Language (extensible Markup Language): Store data and transfer array 2 as with JSON parsing, often used in interactive data formats
3 Generic XML documents (XML document)
4 Examples:
<student> "tags, indicating start"
<name> you </name>
</student> "label, end of expression"
5 syntax for XML documents:
5.1 Document declaration: At the front of the XML document, you must write a document declaration
A simplest statement: <?xml Version = "1.0"?>
b Use the encoding attribute to describe the document character encoding: <?xml Version = "1.0" encoding = "UTF-8"?>
5.2 element: An element that contains a start tag and an end tag
A have all content:<name> you </name>
b No element content:<name></name>
and an element can nest several child elements, but not cross-nested
<students>
<student> "tags, indicating start"
<name> you </name>
</student> "label, end of expression"
<stdudents>
* * Note: The 1 canonical XML document has at most one root element, and the other is the descendant element of the root element.
2 in XML, spaces and line breaks are treated as concrete content, such as: A and B are not the same
A <name> you </name>
b <name>
You
</name>
5.3 Attribute (Atribute): An element can have multiple properties, such as
<video name= "Small Yellow Man" hobby= "Apple"/> "video element has name,hobby two properties"
* Note: The value of the attribute must be "or" enclosed
* Properties represent information that can also be represented by child elements, for example:
<video>
<name> Small yellow people </name>
</video>
6 parsing of XML documents:
Extract the contents of the name element:<name> Yellow </name>
Or extract the value of name and hobby in the video element: <video name= "Yellow Man" hobby= "Apple"/>
7---SAX parsing----simple API for XML
Sax: Event-driven parsing, row-by-line parsing of data (with protocol callback mechanism) Nsxmlparser is an XML parsing class that comes with IOS, and the parsing of data using SAX method is callback by Nsxmlparserdelegate protocol <students >
<student>
<name> you </name>
</student>
</students>
A parsing method, line by row to parse.
A.1 Opening an XML document
A.2 start node (start tag)
A.3 row-by-line parsing
A.4 discover what's inside the element
A.5 Extract Content
A.6 End node (end tag)
A.7 Loop starts until the end tag of the root element is encountered, parsing is completely over B IOS has much more parsing methods in XML
B.1 Apple native: Nsxmlparser-SAX method parsing, simple to use
B.2 third-Party framework: 1 LIBXM12: pure C language, the default is included in the IOS SDk 2 gdataxml:D om parsing method, is developed by Google, the bottom layer based on LIBXML2 8---DOM parsing----a Document The object model, which reads the entire XML document, constructs the tree result (number of nodes) that resides in memory, reads its properties and values by traversing any XML node in the tree structure, and typically, with XPath, directly queries the XML Node B step: B.1 gets gdataxmlnode.h/m file, add GDATAXMLNODE.M to the desired project B.2 Add Class library libxml2.tbd to the Project Libxml2.dylib (iOS7) B.3 in the project "Build Settings" page Find "Header Search Path" entry, add/usr/include/libxml2b.4 import GDataXMLNode.h file to header file, such as compile successfully, then Gdataxmlnode Add success C property and method name tag name a Ttributeforname the attribute node stringvalue the string between tags rootelement child nodes three JSON data structure1 JSON (JavaScript Object Notation), lightweight data Interchange format, is based on a subset of JS, is completely in a separate language text format, easy to read and write, easy machine parsing and generation, very suitable for server and client interaction 2 Note: Standard JSON format: Key must use the data type in the syntax 3.1 of the double quotation mark 3 JSON data structure: string, numeric, BOOL, object, array 3.2 files have two structures: object, array 3.3 Json-oc: The data type A in JSON that corresponds to a large enclosing Number {}, nsdictionary in OC
square brackets in the b JSON [], expressed in OC Nsarray C JSON in the double quotation mark "", in OC represents the NSSTRING4 JSON data structure of the function of data interchange, content management, configuration file 5 in IOS Common JSON parsing method: 5 .1 Soundtrack: Nsjsonserialization (best-performing) nsjsonserialization contains two methods to parse JSON data in different data forms 5.1.1 +jsonobjectwithdata:op Tions:error: Parsing JSON5.1.2 +writejsonobject:tostream:options:error using buffer data: Parsing JSON with a file stream in line 5.2 third-party: Jsonkit, Sbjson, Touchjson (from left to right, getting worse) Objectfromjsondata four XML and JSON two data structure advantages and disadvantages advantages and disadvantages of the 1.XML and JSON two data structures

1> XML
Advantages: \u2028

    • Uniform format, conforms to standard \u2028

    • Easy to interact with other systems remotely, data sharing is more convenient

\u2028 Disadvantages:

    • XML file Format file is large, complex format, transmission occupied bandwidth \u2028

    • Both the server side and the client need to spend a lot of code parsing XML, whether the server side and client code becomes unusually complex and difficult to maintain

    • The client is different, parsing the XML between browsers is inconsistent, you need to write a lot of code repeatedly \u2028

    • Server side and client parsing XML spend resources and time

2> JSON
Advantages: \u2028

    • Data format is simple, easy to read and write, the format is compressed, occupy a small bandwidth \u2028

    • Easy to parse the language

    • Support multiple languages, including ActionScript, C, C #, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and other languages server-side language, easy server-side parsing \u2028

    • Because the JSON format can be used directly for server-side code, greatly simplifies the server-side and client code development, but the completion of the task is not changed, and easy to maintain \u2028

Cons: \u2028

    • There is no XML format so popularized and widely used, without XML so universal \u2028

    • The JSON format is currently promoted in the Web service as an initial stage

2.JSON, the bottom-level implementation of XML parsing method

1> XML

XML two parsing methods, DOM and SAX.

The DOM needs to read through the entire XML document (document-driven), Sax is event-driven, does not need to read the entire document, and the document's read-in process is the SAX parsing process.

SAX is simply a sequential scan of the XML document, when scanning to the beginning and end of the document, the beginning and end of the element, it will trigger the corresponding event handler function, the event handler function to do the corresponding action, after processing to continue scanning until the end of the document, the resolution is complete

When the DOM parses an XML file, it reads all the contents of the XML file into memory, and then allows you to manipulate the XML tree using the DOM API. That is, the DOM will read the XML into memory as a tree, and then manipulate the XML tree through the corresponding API to achieve the purpose of parsing the XML file.

2> JSON

The JSON underlying principle iterates through the characters in the string, and is eventually differentiated by special help characters such as {},[],: number, {} is a dictionary, [] represents an array, the number is a watershed of the dictionary's key and value, and finally the JSON data is converted to a dictionary, then the dictionary is transformed into a model using KVC

3 Selection Recommendations

1) for complex data structures using XML, a simple data structure can be JSON-based.

2) The use of JSON is advocated in data transmission in Internet applications.

3) for the difference between the front and back, you can use XML on the server side, using JSON at the front end, the conversion between the two is done on the servers. So you can take the director.

JSON data structure

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.