json配列を書式設定してサーバーに送信しようとしていました。私は以下のコードを試して、正しい文字列出力を得ました。Cのforループを使用したJson配列のjsonオブジェクトの書式設定
json_t* json_arr = json_array();
json_t* json_request = json_object();
json_t* json_request1 = json_object();
json_t* host = json_object();
json_t* host1 = json_object();
char *buf;
json_object_set_new(json_request, "mac", json_string("005056BD3B6C"));
json_object_set_new(host, "os_type", json_string("Linux_Fedora"));
json_object_set_new(host, "user_agent", json_string("Wget/1.10.2 (Fedora modified)"));
json_object_set_new(json_request1, "mac", json_string("005056BD3B60"));
json_object_set_new(host1, "os_type", json_string("Linux_Fedora"));
json_object_set_new(host1, "user_agent", json_string("Wget/1.10.2 (Fedora modified)"));
json_object_set_new(json_request ,"host", host);
json_object_set_new(json_request1 ,"host", host1);
json_array_append(json_arr ,json_request);
json_array_append(json_arr ,json_request1);
buf = json_dumps(json_arr ,JSON_PRESERVE_ORDER);
出力:
[
{
"mac":"005056BD3B6C",
"host":{
"os_type":"Linux_Fedora",
"user_agent":"Wget/1.10.2 (Fedora modified)"
}
},
{
"mac":"005056BD3B60",
"host":{
"os_type":"Linux_Fedora",
"user_agent":"Wget/1.10.2 (Fedora modified)"
}
}
]
私は、私は以下のコードを試してみました、私のrequirement.soごとにループ内で上記のコードを入れたかったです。
[
{
"mac":"005056b4800c",
"host":{
"mac":"005056b4801c",
"host":{
"mac":"005056b4802c",
"host":{
}
}
}
},
{
"mac":"005056b4801c",
"host":{
"mac":"005056b4802c",
"host":{
}
}
},
{
"mac":"005056b4802c",
"host":{
}
}
]
どのように私は、ループを使用することができますし、上記と同じ配列をフォーマット:
json_t* json_arr = json_array();
char *buf;
const char *str[3];
str[0] = "005056b4800c";
str[1] = "005056b4801c";
str[2] = "005056b4802c";
for (i=0;i<3;i++)
{
json_t* json_request = json_object();
json_t* host = json_object();
json_object_set_new(json_request, "mac", json_string(str[i]));
json_object_set_new(host, "os_type", json_string("Linux_Fedora"));
json_object_set_new(host, "user_agent", json_string("Wget/1.10.2 (Fedora modified)"));
json_object_set_new(json_request ,"host", host);
json_array_append(json_arr ,json_request);
json_decref(json_request);
json_decref(host);
}
buf = json_dumps(json_arr ,JSON_PRESERVE_ORDER);
は、ここで私は以下のバッファ値を得ましたか。
使用しているJSONライブラリを教えてください。それはヤンソンですか? – Gerhardh