導航:首頁 > 編程語言 > 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格式數據格式化相關的資料

熱點內容
圓弧刀東槽如何編程 瀏覽:870
js怎麼單擊改變標簽里的文字 瀏覽:760
實例配置文件里的sid是什麼 瀏覽:43
ps文件模糊 瀏覽:192
葉檀財經推出過什麼購物APP 瀏覽:875
linux硬碟檢測 瀏覽:431
如何用路由器降低網路延遲 瀏覽:601
aix分區root密碼 瀏覽:439
運動鞋買鞋上什麼app 瀏覽:904
NSA工具下載 瀏覽:918
函數代碼在哪個文件夾 瀏覽:213
微信應用怎麼代碼添加快捷方式 瀏覽:371
用數據說話是最有力的什麼 瀏覽:27
圖片文件被鎖定無法打開 瀏覽:768
wr886nv2升級 瀏覽:490
移動硬碟視頻文件無法刪除 瀏覽:417
如何查看網路監控 瀏覽:132
列印機如何連接到網路列印機 瀏覽:181
vmlinux安裝tools 瀏覽:768
波形文件轉mp3 瀏覽:803

友情鏈接