1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Parsonを使用してC言語でJSONファイルを出力

Last updated at Posted at 2021-07-29

はじめに

C言語でJSONを扱う方法を、備忘録として残します。

JSONパーサをダウンロード

JSONパーサにはParson(https://github.com/kgabis/parson)を用いました。

そもそもパーサとは?

パース(parse:解析する)するツールです。
JSONを扱うときに必要なプログラムと思ってください。

必要なファイルは2つだけ

Parsonをダウンロードできたら展開します。
必要なファイルは次の3つのみです。

  • parson.h
  • parson.c
  • tests.c

他にもいろんなファイルがありますが、サンプルで使うファイルであったり、英語の説明書です。
必要に応じて読んでみてください。

具体的なプログラム

それでは、具体的なプログラムを見ていきましょう。

parson.hとparson.cはそのまま使う

parsonを扱うために必要なヘッダファイルと、いろんな定義ファイルなのでそのまま使います。

tests.cから必要な部分のみ残して書き換える

(test.cは初めから削除して、新しくスクリプトシートを作った方が良いかもしれません。かなり改変していますし…)

ここにmain関数が記述されています。
必要な部分を抽出し、コメントを加えて少し変更したプログラムを以下に示します。

# include <stdio.h>
# include "parson.h"

int main(void)
{
    /* 初期化 */
    JSON_Value* my_value = json_value_init_object();
    JSON_Object* my_object = json_value_get_object(my_value);
    
    /* メンバをセット */
    json_object_set_string(my_object, "name", "John Smith");
    json_object_set_number(my_object, "age", 25);
    json_object_dotset_string(my_object, "address.city", "Cupertino");
    json_object_dotset_value(my_object, "contact.emails",
                             json_parse_string("[\"email@example.com\", \"email2@example.com\"]"));
    
    /* コンソールに表示 */
    char* serialized_string = NULL;
    serialized_string = json_serialize_to_string_pretty(my_value);
    puts(serialized_string);
    json_free_serialized_string(serialized_string);
    
    /* JSONからデータを抽出 */
    const char* name = NULL;
    name = json_object_get_string(json_object(my_value), "name");
    printf("Hello, %s.", name);
    
    /* JSON書き出し */
    json_serialize_to_file(my_value, "test_output.json");
    
    /* データ解放 */
    json_value_free(my_value);
    
    return 0;
}

出力データ

プログラムを実行後、コンソールにJSON形式で文字が出力されていたら成功です。
コンソールに出力されている文字と同じものがJSONファイルに出力されています。
構造はここで説明するよりも、自身で色々いじってみる方が理解できると思いますので、割愛します。

{
    "name": "John Smith",
    "age": 25,
    "address": {
        "city": "Cupertino"
    },
    "contact": {
        "emails": [
            "email@example.com",
            "email2@example.com"
        ]
    }
}

まとめ

JSONパーサ「Parson」を使用し、C言語でJSONを出力しました。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?