Lua uses Cjson to read and write JSON samples to share _lua

Source: Internet
Author: User
Tags lua

I'm using the Lua Cjson Library, a high-performance JSON parser and encoder with a 10~20-fold performance over pure LUA libraries. and LUA JSON fully supports UTF-8, without having to do with other Lua/luajit-related packages.

Environment installation

Here is not detailed, ask the Google has a lot of answers.

Sample code

Parsing JSON

Copy Code code as follows:

Local Cjson = require "Cjson"
Local Samplejson = [[{' Age ': '] ', ' Testarray ': {' array ': [8,9,11,14,25]}, ' Himi ': ' himigame.com '}]];
--Parsing the JSON string
Local data = Cjson.decode (Samplejson);
--Print the Age field in the JSON string
Print (data["age"]);
--Print the first value in the array (LUA defaults to count from 0)
Print (data["Testarray"] ["array"][1]);

Encode JSON

Copy Code code as follows:

Local Cjson = require "Cjson"
Local rettable = {}; --a table that eventually produces JSON
--Sequential values
Local intdatas = {};
INTDATAS[1] = 100;
INTDATAS[2] = "100";
--Array
Local arydatas = {};
Arydatas[1] = {};
arydatas[1]["Key 11"] = "value 11";
arydatas[1]["Key 12"] = "value 12";
Arydatas[2] = {};
arydatas[2]["Key 21"] = "value 21";
arydatas[2]["Key 22"] = "value 22";
--Assign value to table
rettable["Key 1"] = "value 1";
RETTABLE[2] = 123;
rettable["Int_datas"] = Intdatas;
rettable["Arydatas"] = Arydatas;
--encode the table data into a JSON string
Local JSONSTR = Cjson.encode (rettable);
Print (JSONSTR);
The result is: {"Int_datas": [100, "100"], "2": 123, "Key 1": "Value 1", "Arydatas": [{"Key 12": "Value 12", "Key 11": "Value 11"},{"key 21": "Value 21", "Key 22": "Value 22 "}]}

Written in the last

The above is only for the Cjson library simple application example, if have any question, please give me the message in time.

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.