JanssonでJSONオブジェクトを並び順に表示するには
Janssonのjson_file_load()関数でJSONファイルを読み込むと、
JSONオブジェクトの中身は、ハッシュテーブル処理の関係ででたらめになりまが、
これを何とかJSONファイルの元の並び順にする方法を見つけましたので報告します。
それはjansson2.5のdump.cの中にやり方が書いてありました。
どおもJSONオブジェクト構造体にシリアル番号らしきメンバ変数があるので、
それを元にソートしてやれば良いみたいです。
// オブジェクトキー配列を作成します。 json_t * json = reinterpret_cast< json_t * >( const_cast< json_object_t * >( pJsonObject ) ), * value; size_t size = json_object_size( json ); struct object_key { size_t serial; const char * key; } * keys = new struct object_key[ size ]; memset( keys, 0, sizeof( struct object_key ) * size ); // JSONオブジェクトを巡回します。 size_t index = 0; for ( void * iter = json_object_iter( json ); iter; iter = json_object_iter_next( json, iter ), index++ ) { // シリアル値とキー文字列ポインタを設定します。 keys[ index ].serial = container_of( iter, hashtable_pair, list )->serial; keys[ index ].key = json_object_iter_key( iter ); } // JSONオブジェクトをシリアル値でソートします。 for ( index = 0; index < size - 1; index++ ) { for ( size_t index2 = index + 1; index2 < size; index2++ ) { if ( keys[ index ].serial > keys[ index2 ].serial ) { struct object_key tmp = keys[ index ]; keys[ index ] = keys[ index2 ]; keys[ index2 ] = tmp; } } } // オブジェクトキー配列を巡回します。 for ( index = 0; index < size; index++ ) { // オブジェクト名を表示します。 printf( "object[ %u ] : %s\n", index, keys[ index ].key ); // オブジェクト値を表示します。 value = json_object_iter_value( json_object_key_to_iter( keys[ index ].key ) ); PrintJsonValue( value ); } // オブジェクトキー配列を削除します。 delete[] keys;
詳細はこちらをご覧ください。
JSONファイルサンプル#1