导航:首页 > 编程语言 > c读取json格式数据格式化

c读取json格式数据格式化

发布时间:2023-07-29 05:53:06

『壹』 格式化输出 jsON

JSON.stringify() 是将 javaScript 对象转换为 JSON 的规范方法。有许多 JavaScript 框架在内部都使用了 JSON.stringify() ,比如 Express 框架的 res.json() 和 Axios body 序列化。

但是,默认情况下, JSON.stringify() 输出的 JSON 格式,不带空格或颜色。在后面,我们将使用一个常用的 npm 包来丰富输出数据的色彩。

JSON.stringify() 基本用法如下:

可以看到,我们使用 JSON.stringify() 输出的内容更具可读性。

你也可以传入一个 " " 制表符间距,格式化输出的数据。

JSON.stringify 的第三个参数用于控制间距。正是它提供了漂亮的字符串输出。

它允许两种类型的参数: Number 和 String 。

如果 Space 是一个 Number 类型,则表示 JSON.stringify 将在每个键之前放置的相应的空格数。可以使用 0 到 10 之间的任意数字作为缩进。

或者,可以使用字符串作为缩进。最多允许10个字符。如果您尝试传递超过10个字符,它将只使用前10个字符。

对于不直接调用 JSON.stringify() 的框架,通常有一个设置 spaces 参数的选项。例如,Express 有一个全局 'json spaces' 选项 ,允许您为所有 res.json() 调用设置 spaces 。

Axios 没有设置 JSON 格式的 显式选项 ,但您可以使用 transformRequest 选项 自行处理 JSON 序列化。关键语法如下:

Prettyjson 以 YAML 样式格式化 JSON 数据。Prettyjson 仅在 CLI 上工作,如果将 Prettyjson 输出作为 HTTP 响应发送,则无法获得颜色。

下面是使用 Prettyjson 从 Node.js 打印 JSON 的示例:

效果如下:

您应该使用以上这类方法来使你想要突出显示的数据以提高可读性。

这里我们额外在说一下 JSON.stringify 的第二个参数 replacer ,我们可以使用它来转换结果。

它允许两种类型的参数: Array 和 Function 。

我们为每一项调用一次 function ,你也可以循环每一项,并在每次传递时使用函数中定义的逻辑进行操作。

下面是一个示例,我跳过了值不是字符串的属性。换句话说,我只想显示值为数字的项。

『贰』 如何使用c语言获取文件中的json数据

直接文件操作就行了。fopen,然后直接读出文件中的json数据,保存到一个数组里面就行了

『叁』 C#怎么从http上返回JSON数据并读取

我之前做过网络和桌面应用的数据对接,你看看
/*
1、对象集合
*/
[DataContract]
publicclassItems
{
[DataMember]
publicList<ddd>ddd{get;set;}
publicItems()
{
ddd=newList<ddd>();
}

//把字符串转换为对象
publicstaticItemsFormJson(stringjson)
{
try
{
System.Runtime.Serialization.Json.DataContractJsonSerializera=newSystem.Runtime.Serialization.Json.DataContractJsonSerializer(typeof(Items));
using(MemoryStreamstream=newMemoryStream(Encoding.Unicode.GetBytes(json)))
{
return(Items)a.ReadObject(stream);
}
}
catch(Exception)
{

returnnull;
}
}
}
/*
简单的对象
*/
[DataContract]
publicclassddd
{
[DataMember]
publicintcid{get;set;}
[DataMember]
publicintpid{get;set;}
[DataMember]
publicintoid{get;set;}
[DataMember]
publicstringview_type{get;set;}
[DataMember]
publicstringstatus{get;set;}
[DataMember]
publicstringname{get;set;}
[DataMember]
publicstringeng_name{get;set;}
[DataMember]
publicstringctpl{get;set;}
[DataMember]
publicstringurl{get;set;}
}


/*
2、从HTTP请求中得到数据
*/

HttpWebRequestrequest=(HttpWebRequest)HttpWebRequest.Create("http://www.bursonchurch.net//index.php?Interface-index-keyt-123-act-catelist.html");
request.Timeout=5000;
request.Method="GET";
HttpWebResponseresponse=(HttpWebResponse)request.GetResponse();
Console.WriteLine("内容类型:"+response.ContentType);
Console.WriteLine("内容长度:"+response.ContentLength);
Console.WriteLine("服务器名:"+response.Server);
Console.WriteLine("资源的URI:"+response.ResponseUri);
Console.WriteLine("HTTP协议版本:"+response.ProtocolVersion);
Console.WriteLine("相应状态:"+response.StatusCode);
Console.WriteLine("相应方法:"+response.Method);
//头信息
for(inti=0;i<response.Headers.Count;++i)
{
Console.WriteLine(" HeaderName:{0},----------Value:{1}",response.Headers.Keys[i],response.Headers[i]);
}

StreamReadersr=newStreamReader(response.GetResponseStream());
stringjsonstr=sr.ReadToEnd();

//例子:假设得到的json数据下面序列化为对象
stringtest="{"ddd":[{"cid":"1","pid":"0","oid":"0","view_type":"0","status":"1","name":"西科推荐","eng_name":"","ctpl":"","ctitle":"","ckeywords":"","cdescription":"","url":"http:\/\/www.bursonchurch.net\/index.php?Cate-index-cid-1.html"},{"cid":"2","pid":"0","oid":"2","view_type":"0","status":"1","name":"校园活动","eng_name":"","ctpl":"","ctitle":"","ckeywords":"","cdescription":"","url":"http:\/\/www.bursonchurch.net\/index.php?Cate-index-cid-2.html"},{"cid":"3","pid":"0","oid":"2","view_type":"0","status":"1","name":"帅哥","eng_name":"","ctpl":"","ctitle":"","ckeywords":"动物世界keword","cdescription":"动物世界s","url":"http:\/\/www.bursonchurch.net\/index.php?Cate-index-cid-3.html"},{"cid":"4","pid":"0","oid":"4","view_type":"1","status":"1","name":"静物","eng_name":"","ctpl":"","ctitle":"","ckeywords":"","cdescription":"","url":"http:\/\/www.bursonchurch.net\/index.php?Cate-index-cid-4.html"},{"cid":"5","pid":"0","oid":"5","view_type":"1","status":"1","name":"美女","eng_name":"","ctpl":"","ctitle":"","ckeywords":"","cdescription":"","url":"http:\/\/www.bursonchurch.net\/index.php?Cate-index-cid-5.html"}]}";

//第一种转
JavaScriptSerializerj=newJavaScriptSerializer();
Itemsii=newItems();
ii=j.Deserialize<Items>(jsonstr);


//第二种也行
Itemsit=Items.FormJson(jsonstr);

response.Close();
Console.ReadKey();

『肆』 C#字符串转成JSON对象,并解析出里面的数据

构造对象:

public struct ToJsonMy

{

public string result { get; set; } //属性的名字,必须与json格式字符串中的"key"值一样。

public string res_info { get; set; }

public string queryorder_info { get; set; } }

转换过程:

public static void JsonMy()

{

string json = Jsonstr("D:\json\jsonmy1.txt");//Jsonstr函数读取json数据的文本txt

JavaScriptSerializer js = new JavaScriptSerializer(); //实例化一个能够序列化数据的类

ToJsonMy list = js.Deserialize<ToJsonMy>(json); //将json数据转化为对象类型并赋值给list

string result = list.result;

string res_info = list.res_info;

string queryorder_info = list.res_info;

}

『伍』 C++解析Json字符串问题!

一、从字符串中读取JSON
#include <iostream>
#include "json/json.h"
using namespace std;
int main()
{
//字符串
const char * str =
"{\"praenomen\":\"Gaius\",\"nomen\":\"Julius\",\"cognomen\":\"Caezar\","
"\"born\":-100,\"died\":-44}" ;
Json::Reader reader;
Json::Value root;
//从字符串中读取数据
if (reader.parse(str,root))
{
string praenomen = root[ "praenomen" ].asString();
string nomen = root[ "nomen" ].asString();
string cognomen = root[ "cognomen" ].asString();
int born = root[ "born" ].asInt();
int died = root[ "died" ].asInt();
cout << praenomen + " " + nomen + " " + cognomen
<< " was born in year " << born
<< ", died in year " << died << endl;
}
return 0;
}

makefile文件
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

二、从文件中读取JSON
PersonalInfo.json(一个存储了JSON格式字符串的文件)

{
"name" : "Tsybius" ,
"age" :23,
"sex_is_male" : true ,
"partner" :
{
"partner_name" : "Galatea" ,
"partner_age" :21,
"partner_sex_is_male" : false
},
"achievement" :[ "ach1" , "ach2" , "ach3" ]
}
#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main()
{
Json::Reader reader;
Json::Value root;
//从文件中读取
ifstream is;
is.open( "PersonalInfo.json" , ios::binary);
if (reader.parse(is,root))
{
//读取根节点信息
string name = root[ "name" ].asString();
int age = root[ "age" ].asInt();
bool sex_is_male = root[ "sex_is_male" ].asBool();
cout << "My name is " << name << endl;
cout << "I'm " << age << " years old" << endl;
cout << "I'm a " << (sex_is_male ? "man" : "woman" ) << endl;
//读取子节点信息
string partner_name = root[ "partner" ][ "partner_name"].asString();
int partner_age = root[ "partner" ][ "partner_age" ].asInt();
bool partner_sex_is_male = root[ "partner" ]["partner_sex_is_male" ].asBool();
cout << "My partner's name is " << partner_name << endl;
cout << (partner_sex_is_male ? "he" : "she" ) << " is "
<< partner_age << " years old" << endl;
//读取数组信息
cout << "Here's my achievements:" << endl;
for ( int i = 0; i < root[ "achievement" ].size(); i++)
{
string ach = root[ "achievement" ][i].asString();
cout << ach << '\t' ;
}
cout << endl;
cout << "Reading Complete!" << endl;
}
is.close();
return 0;
}

makefile
?
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

三、将信息保存为JSON格式
a.cpp

#include <iostream>
#include <fstream>
#include "json/json.h"
using namespace std;
int main()
{
//根节点
Json::Value root;
//根节点属性
root[ "name" ] = Json::Value( "Tsybius" );
root[ "age" ] = Json::Value(23);
root[ "sex_is_male" ] = Json::Value( true );
//子节点
Json::Value partner;
//子节点属性
partner[ "partner_name" ] = Json::Value( "Galatea" );
partner[ "partner_age" ] = Json::Value(21);
partner[ "partner_sex_is_male" ] = Json::Value( false );
//子节点挂到根节点上
root[ "partner" ] = Json::Value(partner);
//数组形式
root[ "achievement" ].append( "ach1" );
root[ "achievement" ].append( "ach2" );
root[ "achievement" ].append( "ach3" );

//直接输出
cout << "FastWriter:" << endl;
Json::FastWriter fw;
cout << fw.write(root) << endl << endl;
//缩进输出
cout << "StyledWriter:" << endl;
Json::StyledWriter sw;
cout << sw.write(root) << endl << endl;

//输出到文件
ofstream os;
os.open( "PersonalInfo" );
os << sw.write(root);
os.close();
return 0;
}

makefile
LIB=-L /usr/local/lib/libjson/ -ljson_linux- gcc -4.4.7_libmt
a: a.o
g++ -o a -std=c++0x a.o $(LIB)
a.o: a.cpp
g++ -c a.cpp
clean:
rm -rf a.o a

{
"achievement" : [ "ach1" , "ach2" , "ach3" ],
"age" : 23,
"name" : "Tsybius" ,
"partner" : {
"partner_age" : 21,
"partner_name" : "Galatea" ,
"partner_sex_is_male" : false
},
"sex_is_male" : true
}

『陆』 vscode怎么格式化js中的json数据

你可以把你的JSON数据贴出来
网络JSON在线格式化 然后拖进去格式化再贴回去就行了 有的无法格式化可能是按键冲突了

『柒』 C语言读取多行json文件数据 用哪种库比较好, 具体怎么操作

有的来是自 下面是超市 请自选 JSON_checker. YAJL. js0n. LibU. json-c. json-parser. jsonsl. WJElement. M's JSON parser. cJSON. Jansson. jsmn. cson. parson. ujson4c. nxjson.

『捌』 如何读取Json文件的数据

json文件是一种轻量级的数据交互格式。一般在jquery中使用getJSON()方法读取。

$.getJSON(url,[data],[callback])
url:加载的页面地址
data: 可选项,发送到服务器的数据,格式是key/value
callback:可选项,加载成功后执行的回调函数
1.首先建一个JSON格式的文件userinfo.json 保存用户信息。如下:

?

1234567891011121314151617

[{"name":"张国立","sex":"男","email":"[email protected]"},{"name":"张铁林","sex":"男","email":"[email protected]"},{"name":"邓婕","sex":"女","email":"[email protected]"}]

2.其次建一个页面用于获取JSON文件里的用户信息数据,并显示

?

04142
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>getJSON获取数据</title><script type="text/javascript" src="js/jquery-1.8.2.min.js"></script><style type="text/css">#divframe{ border:1px solid #999; width:500px; margin:0 auto;}.loadTitle{ background:#CCC; height:30px;}</style>< script type = "text/javascript" >$(function (){ $("#btn").click(function () { $.getJSON("js/userinfo.json", function (data){ var $jsontip = $("#jsonTip"); var strHtml = "123"; //存储数据的变量 $jsontip.empty(); //清空内容 $.each(data, function (infoIndex, info){ strHtml += "姓名:" + info["name"] + "<br>"; strHtml += "性别:" + info["sex"] + "<br>"; strHtml += "邮箱:" + info["email"] + "<br>"; strHtml += "<hr>" }) $jsontip.html(strHtml); //显示处理后的数据 }) })})</script></head><body><div id="divframe"><div class="loadTitle"><input type="button" value="获取数据" id="btn"/></div><div id="jsonTip"></div></div></body></html>

『玖』 怎么用C语言获取JSON中的数据

用C语言获取JSON中的数据的方法是使用 CJSON。

以下简单介绍用CJSON的思路及实现:

1)创建json,从json中获取数据。

#nclude <stdio.h>

#include "cJSON.h"

char * makeJson()

{

cJSON * pJsonRoot = NULL;


pJsonRoot = cJSON_CreateObject();

if(NULL == pJsonRoot)

{

//error happend here

return NULL;

}

cJSON_AddStringToObject(pJsonRoot, "hello", "hello world");

cJSON_AddNumberToObject(pJsonRoot, "number", 10010);

cJSON_AddBoolToObject(pJsonRoot, "bool", 1);

cJSON * pSubJson = NULL;

pSubJson = cJSON_CreateObject();

if(NULL == pSubJson)

{

// create object faild, exit

cJSON_Delete(pJsonRoot);

return NULL;

}

cJSON_AddStringToObject(pSubJson, "subjsonobj", "a sub json string");

cJSON_AddItemToObject(pJsonRoot, "subobj", pSubJson);

char * p = cJSON_Print(pJsonRoot);

// else use :

// char * p = cJSON_PrintUnformatted(pJsonRoot);

if(NULL == p)

{

//convert json list to string faild, exit

//because sub json pSubJson han been add to pJsonRoot, so just delete pJsonRoot, if you also delete pSubJson, it will coremp, and error is : double free

cJSON_Delete(pJsonRoot);

return NULL;

}

//free(p);

cJSON_Delete(pJsonRoot);

return p;

}

void parseJson(char * pMsg)

{

if(NULL == pMsg)

{

return;

}

cJSON * pJson = cJSON_Parse(pMsg);

if(NULL == pJson)

{

// parse faild, return

return ;

}

// get string from json

cJSON * pSub = cJSON_GetObjectItem(pJson, "hello");

if(NULL == pSub)

{

//get object named "hello" faild

}

printf("obj_1 : %s ", pSub->valuestring);

// get number from json

pSub = cJSON_GetObjectItem(pJson, "number");

if(NULL == pSub)

{

//get number from json faild

}

printf("obj_2 : %d ", pSub->valueint);

// get bool from json

pSub = cJSON_GetObjectItem(pJson, "bool");

if(NULL == pSub)

{

// get bool from json faild

}

printf("obj_3 : %d ", pSub->valueint);

// get sub object

pSub = cJSON_GetObjectItem(pJson, "subobj");

if(NULL == pSub)

{

// get sub object faild

}

cJSON * pSubSub = cJSON_GetObjectItem(pSub, "subjsonobj");

if(NULL == pSubSub)

{

// get object from subject object faild

}

printf("sub_obj_1 : %s ", pSubSub->valuestring);

cJSON_Delete(pJson);

}


int main()

{

char * p = makeJson();

if(NULL == p)

{

return 0;

}

printf("%s ", p);

parseJson(p);

free(p);//这里不要忘记释放内存,cJSON_Print()函数或者cJSON_PrintUnformatted()产生的内存,使用free(char *)进行释放

return 0;

}

2)创建json数组和解析json数组

//创建数组,数组值是另一个JSON的item,这里使用数字作为演示

char * makeArray(int iSize)

{

cJSON * root = cJSON_CreateArray();

if(NULL == root)

{

printf("create json array faild ");

return NULL;

}

int i = 0;


for(i = 0; i < iSize; i++)

{

cJSON_AddNumberToObject(root, "hehe", i);

}

char * out = cJSON_Print(root);

cJSON_Delete(root);


return out;

}

//解析刚刚的CJSON数组

void parseArray(char * pJson)

{

if(NULL == pJson)

{

return ;

}

cJSON * root = NULL;

if((root = cJSON_Parse(pJson)) == NULL)

{

return ;

}

int iSize = cJSON_GetArraySize(root);

for(int iCnt = 0; iCnt < iSize; iCnt++)

{

cJSON * pSub = cJSON_GetArrayItem(root, iCnt);

if(NULL == pSub)

{

continue;

}

int iValue = pSub->valueint;

printf("value[%2d] : [%d] ", iCnt, iValue);

}

cJSON_Delete(root);

return;

}

阅读全文

与c读取json格式数据格式化相关的资料

热点内容
macbookpro如何修改文件内容 浏览:965
java稳定排序 浏览:53
oppo文件管理的图片 浏览:335
plc编程步数怎么计算 浏览:142
ipad看电脑文件 浏览:935
成都制作pdf文件 浏览:735
怎么样点开电脑里面的网络连接 浏览:755
微信怎么退出账号 浏览:32
w微信开发者工具 浏览:325
数据库还原附加 浏览:713
打包成exe执行文件 浏览:652
信丰营销app有哪些 浏览:463
苹果文件下载项如何下载 浏览:179
ps抠婚纱教程 浏览:203
如何在移动硬盘上隐藏文件夹 浏览:451
瑞虎8老车机怎么刷app 浏览:992
学ui设计要学java吗 浏览:275
淘宝票房数据源怎么调整 浏览:470
iphone5s升级ios卡黑屏 浏览:622
u盘没用的文件删不了怎么办 浏览:561

友情链接