目录
json的官网:包含所有语言 http://json.org/
1、------------------json介绍--两种结构形式
2、--------------------python json模块的使用
2.1、Encoding (官网这么说的)dumps方法:其实就是将数据内容及格式转换成字符串
json的官网:包含所有语言 http://json.org/
1、------------------json介绍--两种结构形式
python字典结构样式的
json就是python的字典结构,如下代码:JavaScript
{
"errorCode1":0,
"reason":"OK",
"result":
{"userId":10099380,"name":"shaofa"},
"numbers":[123,122,238,89]
}
python列表形式的结构
[1,2,'a',1.1]
2、--------------------python json模块的使用
2.1、Encoding (官网这么说的)dumps方法:其实就是将数据内容及格式转换成字符串
用法参考下面网址:
https://blog.csdn.net/liangxy2014/article/details/78985057
import json
#将python的数据内容转换成字符串
json.dumps(['foo', {'bar': ('baz', None, 1.0, 2)}])#'["foo", {"bar": ["baz", null, 1.0, 2]}]'
json.dumps([1,2,3]) # '[1, 2, 3]'
#注意转义字符的使用
print(json.dumps("\"foo\bar")) # "\"foo\bar"
#可以使用sort_keys参数排序
json.dumps({"c": 0, "b": 0, "a": 0}, sort_keys=True) # '{"a": 0, "b": 0, "c": 0}'
#参数介绍:
https://blog.csdn.net/liangxy2014/article/details/78985057
2.2 解码:Decoding JSON:
解码字典
import json
json.loads('["foo", {"bar":["baz", null, 1.0, 2]}]')#['foo', {'bar': ['baz', None, 1.0, 2]}]
解码json列表形式
from io import StringIO
io = StringIO('["streaming API"]')
json.load(io) # ['streaming API']
from io import StringIO
io = StringIO('[1,2,3]')
json.load(io) # [1, 2, 3]
3、c++ rapidjson 处理json方法:
和python不一样:python自带的内置模块很好的处理json数据。c++必须要上官网下载头文件以及相应的cpp文件才可以。
去官网找发现有许多api函数库,这里我们选择阿发你好推荐的rapidjson库。
在vs2008和vs2012上面都通过了,源码复制过去的,文件复制过去的,一动没动。
这里复习一下vs的使用方法:
1,新建win32控制台程序--》空项目--》新建main.cpp文件
2,将json函数库导入和main.cpp一个目录里---》在vs界面工程中新建添加筛选器,将json下载的文件添加进来(包括头文件和cpp文件)
下面写入main.cpp的代码
/* rapid json support */
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
/* stl support*/
#include <iostream>
#include <string>
using namespace std;
// 从文件中读取字符串
string readfile (const char* filename)
{
FILE* fp = fopen(filename, "rb");
if(!fp)
{
printf("failed to open file! file: %s" , filename);
return "";
}
char* buf = new char[1024*16];
int n = fread(buf, 1, 1024*16, fp);
fclose(fp);
string result;
if(n >= 0)
result.append(buf, 0, n);
delete [] buf;
return result;
}
int parseJSON (const char* jsonstr)
{
Document d;
if (d.Parse(jsonstr).HasParseError())
{
printf("parse error!\n");
return -1;
}
if(!d.IsObject())
{
printf("should be an object!\n");
return -1;
}
if(d.HasMember("errorCode"))
{
Value& m = d["errorCode"];
int v = m.GetInt();
printf("errorCode: %d\n", v);
}
printf("show numbers:\n");
if(d.HasMember("numbers"))
{
Value& m = d["numbers"];
if(m.IsArray())
{
for(int i=0; i<m.Size(); i++)
{
Value& e = m[i];
int n = e.GetInt();
printf("%d,", n);
}
}
}
return 0;
}
int parseJSON2 (const char* jsonstr) //这个函数是改进的parseJSON2 ,用异常提示用户那里错误了
{
Document d;
if (d.Parse(jsonstr).HasParseError())
throw string("parse error!");
if(!d.IsObject())
throw string("should be an object!\n");
if(!d.HasMember("errorCode"))
throw string("'errorCode' not found!");
Value& m = d["errorCode"];
int v = m.GetInt();
printf("errorCode: %d\n", v);
printf("show numbers:\n");
if(d.HasMember("numbers"))
{
Value& m = d["numbers"];
if(m.IsArray())
{
for(int i=0; i<m.Size(); i++)
{
Value& e = m[i];
int n = e.GetInt();
printf("%d,", n);
}
}
}
return 0;
}
int main()
{
//将文本中的json结构读取进来,并打印出来看看
string jsonstr = readfile("example.json");
printf("%s", jsonstr.c_str());
//解码:将文本的数据转换成数值型的了。
parseJSON(jsonstr.c_str());
// try{
// parseJSON2(jsonstr.c_str());
// }catch(string& e)
// {
// printf("解析错误: %s \n", e.c_str());
// }
return 0;
}
rapidjson 的使用--简单的字典形式
编码:转换成字符结构
{
"id": 1001,
"name": "shaofa"
"login": true,
"extras": null
}
// rapidjson/example/simpledom/simpledom.cpp`
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
#include <iostream>
#include <string>
using namespace std;
using namespace rapidjson;
string toString(const Document& d)
{
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
string str = buffer.GetString();
return str;
}
int main() {
Document d; # 设置一个json框架,
Document::AllocatorType& allocator = d.GetAllocator();//引用一个内存管理对象,不用管为什么,照抄就可以
d.SetObject();//这句话很关键,是设置成字典结构
d.AddMember("id", 1001, allocator);//添加一个成员
d.AddMember("name", "shaofa", allocator);
d.AddMember("login", true, allocator);
string str = toString(d); //转换成字符结构
printf(str.c_str());
return 0;
}
编码复杂的字典结构--字典中带有字典和列表
{
"errorCode": 0,
"reason": "OK",
"result":
{
"userId": 10099380,
"name": "shaofa"
},
"numbers": [ 123, 122, 238, 089 ]
}
#include "rapidjson/document.h"
#include "rapidjson/writer.h"
#include "rapidjson/stringbuffer.h"
using namespace rapidjson;
/* stl support*/
#include <iostream>
#include <string>
using namespace std;
string toString(const Document& d)
{
StringBuffer buffer;
Writer<StringBuffer> writer(buffer);
d.Accept(writer);
string str = buffer.GetString();
return str;
}
int main()
{
Document d;
Document::AllocatorType& allocator = d.GetAllocator();
d.SetObject(); // 第一层次,document有两种表示方式:一个是{}形式,一种是[]形式
// SetObject是表示设置成{}形式
d.AddMember("errorCode", 0, allocator);
d.AddMember("reason", "OK", allocator);
//添加复杂的成员
if(1)
{
Value v; //创建一个复杂的成员
v.SetObject();//设置这个复杂成员为字典结构
v.AddMember("userId", 10099380,allocator);//添加成员
v.AddMember("name", "shaofa", allocator);
d.AddMember("result", v, allocator);//将这个复杂的字典结构添加到上一层中
}
if(1)
{
Value v;
v.SetArray(); //将这个复杂的结构设置为列表形式
v.PushBack(123, allocator);
v.PushBack(122, allocator);
v.PushBack(238, allocator);
v.PushBack(89, allocator);
d.AddMember("numbers", v, allocator);
}
string str = toString(d);
printf(str.c_str());
return 0;
}