//----------------------------------------------------------------// json_t* _luaToJSONObject ( lua_State* L, int idx ) { MOAILuaState state ( L ); json_t* object = json_object (); u32 itr = state.PushTableItr ( idx ); while ( state.TableItrNext ( itr )) { if ( lua_type ( state, -2 ) != LUA_TSTRING ) continue; STLString key = lua_tostring ( state, -2 ); json_t* value = _luaToJSON ( state, -1 ); if ( value ) { json_object_set_new ( object, key, value ); } } return object; }
static void get_user_playlists(sp_playlistcontainer *pc, struct evhttp_request *request, void *userdata) { json_t *json = json_object(); json_t *playlists = json_array(); json_object_set_new(json, "playlists", playlists); for (int i = 0; i < sp_playlistcontainer_num_playlists(pc); i++) { sp_playlist *playlist = sp_playlistcontainer_playlist(pc, i); if (!sp_playlist_is_loaded(playlist)) // TODO(liesen): Wait for it to load? continue; json_t *playlist_json = json_object(); playlist_to_json(playlist, playlist_json); json_array_append_new(playlists, playlist_json); } send_reply_json(request, HTTP_OK, "OK", json); }
static json_t *btcity_toJson(const void *vc) { btcity_t *btc = (btcity_t *)vc; json_t *root; json_t *node; root = json_object(); JSON_BTSTRING(root, "title", btc->title); JSON_BTSTRING(root, "guildExitSquare", btc->guildExitSquare); JSON_BTSTRING(root, "guildExitDir", btc->guildExitDir); json_object_set_new(root, "squares", cnvList_toJsonObject(btc->sqs)); json_object_set_new(root, "buildings", cnvList_toJsonObject(btc->bls)); node = json_object(); json_object_set_new(node, "items", cnvList_toJsonArray(btc->day->items)); json_object_set_new(node, "monsters", cnvList_toJsonArray(btc->day->monsters)); JSON_NUMBER(node, "poisonDamage", btc->day->poisonDmg); JSON_NUMBER(node, "level", btc->day->level); if (btc->params) json_object_update(node, paramList_toJson(btc->params)); json_object_set_new(root, "day", node); if (btc->night->level) { node = json_object(); json_object_set_new(node, "items", cnvList_toJsonArray(btc->night->items)); json_object_set_new(node, "monsters", cnvList_toJsonArray(btc->night->monsters)); JSON_NUMBER(node, "poisonDamage", btc->night->poisonDmg); JSON_NUMBER(node, "level", btc->night->level); json_object_set_new(root, "night", node); } return root; }
/* * Add an iCalendar parameter to an existing JSON object. */ static void icalparameter_as_json_object_member(icalparameter *param, json_t *jparams) { icalparameter_kind kind; const char *kind_string, *value_string; kind = icalparameter_isa(param); switch (kind) { case ICAL_X_PARAMETER: kind_string = icalparameter_get_xname(param); break; #ifdef HAVE_IANA_PARAMS case ICAL_IANA_PARAMETER: kind_string = icalparameter_get_iana_name(param); break; #endif default: kind_string = icalparameter_kind_to_string(kind); if (kind_string) break; case ICAL_NO_PARAMETER: case ICAL_ANY_PARAMETER: icalerror_set_errno(ICAL_BADARG_ERROR); return; } /* XXX Need to handle multi-valued parameters */ value_string = icalparameter_get_xvalue(param); if (!value_string) { icalparameter_value value = icalparameter_get_value(param); if (value) value_string = icalparameter_enum_to_string(value); } if (!value_string) return; json_object_set_new(jparams, lcase(icalmemory_tmp_copy(kind_string)), json_string(value_string)); }
static void output_json_txout(json_t *arr, const struct bp_txout *txout, unsigned int n_idx) { json_t *obj = json_object(); assert(obj != NULL); char raw_valstr[VALSTR_SZ]; btc_decimal(raw_valstr, VALSTR_SZ, txout->nValue); double raw_val = strtod(raw_valstr, NULL); json_t *val = json_real(raw_val); assert(val != NULL); int rc = json_object_set_new(obj, "value_FIXME", val); assert(rc == 0); bp_json_set_new_int(obj, "n", n_idx); bp_json_set_new_script(obj, "scriptPubKey", txout->scriptPubKey); json_array_append_new(arr, obj); }
/** Handle the case where no JSON support is compiled in. * */ static void AlertJsonHttp(const Flow *f, json_t *js) { HtpState *htp_state = (HtpState *)FlowGetAppState(f); if (htp_state) { uint64_t tx_id = AppLayerParserGetTransactionLogId(f->alparser); htp_tx_t *tx = AppLayerParserGetTx(IPPROTO_TCP, ALPROTO_HTTP, htp_state, tx_id); if (tx) { json_t *hjs = json_object(); if (unlikely(hjs == NULL)) return; JsonHttpLogJSONBasic(hjs, tx); JsonHttpLogJSONExtended(hjs, tx); json_object_set_new(js, "http", hjs); } } return; }
static bool sig_done(jose_io_t *io) { io_t *i = containerof(io, io_t, io); size_t len = 0; if (EVP_DigestSignFinal(i->emc, NULL, &len) <= 0) return false; uint8_t buf[len]; if (EVP_DigestSignFinal(i->emc, buf, &len) <= 0) return false; if (json_object_set_new(i->sig, "signature", jose_b64_enc(buf, len)) < 0) return false; return add_entity(i->obj, i->sig, "signatures", "signature", "protected", "header", NULL); }
/** * Start a new counter by setting the number of sheeps to a specific value * return the current number of sheeps in a json object */ int callback_sheep_counter_start (const struct _u_request * request, struct _u_response * response, void * user_data) { json_t * json_nb_sheep = json_object_get(request->json_body, "nbsheep"); #if JSON_INTEGER_IS_LONG_LONG long long * nb_sheep = user_data; #else long * nb_sheep = user_data; #endif if (json_nb_sheep != NULL) { * nb_sheep = json_integer_value(json_nb_sheep); } else { * nb_sheep = 0; } response->json_body = json_object(); json_object_set_new(response->json_body, "nbsheep", json_integer(* nb_sheep)); response->status = 200; json_decref(json_nb_sheep); return U_OK; }
static void test_equal_object() { json_t *object1, *object2; object1 = json_object(); object2 = json_object(); if(!object1 || !object2) fail("unable to create objects"); if(!json_equal(object1, object2)) fail("json_equal fails for two empty objects"); json_object_set_new(object1, "a", json_integer(1)); json_object_set_new(object2, "a", json_integer(1)); json_object_set_new(object1, "b", json_string("foo")); json_object_set_new(object2, "b", json_string("foo")); json_object_set_new(object1, "c", json_integer(2)); json_object_set_new(object2, "c", json_integer(2)); if(!json_equal(object1, object2)) fail("json_equal fails for two equal objects"); json_object_del(object2, "c"); if(json_equal(object1, object2)) fail("json_equal fails for two inequal objects"); json_object_set_new(object2, "c", json_integer(3)); if(json_equal(object1, object2)) fail("json_equal fails for two inequal objects"); json_object_del(object2, "c"); json_object_set_new(object2, "d", json_integer(2)); if(json_equal(object1, object2)) fail("json_equal fails for two inequal objects"); json_decref(object1); json_decref(object2); }
/// Indexing helpers /// ---------------- // Adds an individual zipped file to the index. // Expects the file name at the current file pointer of [zip->hArc]. static int zip_file_add(zip_t *zip, zip_file_shared_t *zf, json_int_t offset) { int ret = -1; if(zip && zf) { DWORD byte_ret; VLA(char, fn, zf->fn_len + 1); ReadFile(zip->hArc, fn, zf->fn_len, &byte_ret, NULL); fn[zf->fn_len] = 0; SetFilePointer(zip->hArc, zf->extra_len, NULL, FILE_CURRENT); if(zf->fn_len) { if(zf->size_compressed != 0) { json_object_set_new(zip->files, fn, json_integer(offset)); } else { char last = fn[zf->fn_len - 1]; if(last != '/' && last != '\\') { json_array_append_new(zip->files_empty, json_string(fn)); } } } VLA_FREE(fn); ret = 0; }
static json_t *monster_toJson(const void *vm) { json_t *monRoot; monster_t *m = (monster_t *)vm; uint32_t i; monRoot = json_object(); JSON_BTSTRING(monRoot, "singular", m->singular); JSON_BTSTRING(monRoot, "plural", m->plural); JSON_BTSTRING(monRoot, "picture", m->picture); JSON_STRING(monRoot, "pronoun", getPronounString(m->pronoun)); JSON_NUMBER(monRoot, "hpBase", m->hpBase); JSON_NUMBER(monRoot, "hpRndDie", m->hpRndDie); JSON_NUMBER(monRoot, "hpRndNDice", m->hpRndNdice); JSON_NUMBER(monRoot, "reward", m->reward); JSON_NUMBER(monRoot, "ac", m->baseAC); JSON_NUMBER(monRoot, "breathSaveLo", m->breathSaveLo); JSON_NUMBER(monRoot, "breathSaveHi", m->breathSaveHi); JSON_NUMBER(monRoot, "spellSaveLo", m->spellSaveLo); JSON_NUMBER(monRoot, "spellSaveHi", m->spellSaveHi); JSON_NUMBER(monRoot, "toHitLo", m->toHitLo); JSON_NUMBER(monRoot, "toHitHi", m->toHitHi); JSON_NUMBER(monRoot, "priorityLo", m->priorityLo); JSON_NUMBER(monRoot, "priorityHi", m->priorityHi); JSON_BOOL(monRoot, "rndGroupSize", m->rndGroupSize); JSON_NUMBER(monRoot, "groupSize", m->groupSize); JSON_NUMBER(monRoot, "numAttacks", m->numAttacks); /* XXX PRONOUN Handling */ JSON_BOOL(monRoot, "willAdvance", m->willAdvance); JSON_NUMBER(monRoot, "distance", m->distance); JSON_NUMBER(monRoot, "advanceSpeed", m->advSpeed); JSON_BOOL(monRoot, "isIllusion", m->isIllusion); json_object_update(monRoot, repel_toJson(&m->repel)); json_object_set_new(monRoot, "attacks", cnvList_toJsonArray(m->attacks)); return monRoot; }
/** * remove summary (if any) and pipe hat. This is typicaly used for simulations */ void ssm_pipe_hat(FILE *stream, json_t *jparameters, ssm_input_t *input, ssm_hat_t *hat, ssm_par_t *par, ssm_calc_t *calc, ssm_nav_t *nav, ssm_options_t *opts, double t) { int i, index; double x; json_t *jresources = json_object_get(jparameters, "resources"); json_t *jsummary = NULL; int index_summary; for(index=0; index< json_array_size(jresources); index++){ json_t *el = json_array_get(jresources, index); const char* name = json_string_value(json_object_get(el, "name")); if (strcmp(name, "values") == 0) { json_t *values = json_object_get(el, "data"); for(i=0; i<nav->theta_all->length; i++){ x = nav->theta_all->p[i]->f_2prior(gsl_vector_get(input, nav->theta_all->p[i]->offset), hat, par, calc, t); json_object_set_new(values, nav->theta_all->p[i]->name, json_real(x)); } } else if (strcmp(name, "summary") == 0){ jsummary = el; index_summary = index; } } if(jsummary){ json_array_remove(jresources, index_summary); } if(strcmp(opts->next, "") != 0){ char path[SSM_STR_BUFFSIZE]; snprintf(path, SSM_STR_BUFFSIZE, "%s/%s%d.json", opts->root, opts->next, opts->id); json_dump_file(jparameters, path, JSON_INDENT(2)); } else { json_dumpf(jparameters, stdout, JSON_COMPACT); printf("\n"); fflush(stdout); } }
int update_user_balance(bool real, uint32_t user_id, const char *asset, const char *business, uint64_t business_id, mpd_t *change, json_t *detail) { struct update_key key; key.user_id = user_id; strncpy(key.asset, asset, sizeof(key.asset)); strncpy(key.business, business, sizeof(key.business)); key.business_id = business_id; dict_entry *entry = dict_find(dict_update, &key); if (entry) { return -1; } mpd_t *result; mpd_t *abs_change = mpd_new(&mpd_ctx); mpd_abs(abs_change, change, &mpd_ctx); if (mpd_cmp(change, mpd_zero, &mpd_ctx) >= 0) { result = balance_add(user_id, BALANCE_TYPE_AVAILABLE, asset, abs_change); } else { result = balance_sub(user_id, BALANCE_TYPE_AVAILABLE, asset, abs_change); } mpd_del(abs_change); if (result == NULL) return -2; struct update_val val = { .create_time = current_timestamp() }; dict_add(dict_update, &key, &val); if (real) { double now = current_timestamp(); json_object_set_new(detail, "id", json_integer(business_id)); char *detail_str = json_dumps(detail, 0); append_user_balance_history(now, user_id, asset, business, change, detail_str); free(detail_str); push_balance_message(now, user_id, asset, business, change); } return 0; }
int add_collection(json_t *object, const char *coll_name, baton_error_t *error) { init_baton_error(error); if (!json_is_object(object)) { set_baton_error(error, -1, "Failed to add collection data: " "target not a JSON object"); goto error; } json_t *coll = json_pack("s", coll_name); if (!coll) { set_baton_error(error, -1, "Failed to pack data object '%s' as JSON", coll_name); goto error; } return json_object_set_new(object, JSON_COLLECTION_KEY, coll); error: return error->code; }
int add_id_to_object (struct maytrics * maytrics, json_t * json_root, long * id) { json_t * json_id; int status; if (*id == 0) { *id = generate_id (maytrics); } if (*id == -1) { status = EVHTP_RES_SERVERR; goto exit; } json_id = json_integer (*id); if (json_id == NULL) { log_error ("json_integer() failed."); status = EVHTP_RES_SERVERR; goto exit; } if (json_object_set_new (json_root, "id", json_id) == -1) { log_error ("json_object_set() failed."); status = EVHTP_RES_SERVERR; goto json_decref; } return (0); json_decref: json_decref (json_id); exit: return (status); }
static void janus_websockets_destroy_client( janus_websockets_client *ws_client, struct lws *wsi, const char *log_prefix) { if(!ws_client || !g_atomic_int_compare_and_exchange(&ws_client->destroyed, 0, 1)) return; /* Cleanup */ janus_mutex_lock(&ws_client->ts->mutex); JANUS_LOG(LOG_INFO, "[%s-%p] Destroying WebSocket client\n", log_prefix, wsi); ws_client->wsi = NULL; /* Notify handlers about this transport being gone */ if(notify_events && gateway->events_is_enabled()) { json_t *info = json_object(); json_object_set_new(info, "event", json_string("disconnected")); gateway->notify_event(&janus_websockets_transport, ws_client->ts, info); } /* Notify core */ gateway->transport_gone(&janus_websockets_transport, ws_client->ts); ws_client->ts->transport_p = NULL; /* Remove messages queue too, if needed */ if(ws_client->messages != NULL) { char *response = NULL; while((response = g_async_queue_try_pop(ws_client->messages)) != NULL) { g_free(response); } g_async_queue_unref(ws_client->messages); } /* ... and the shared buffers */ g_free(ws_client->incoming); ws_client->incoming = NULL; g_free(ws_client->buffer); ws_client->buffer = NULL; ws_client->buflen = 0; ws_client->bufpending = 0; ws_client->bufoffset = 0; janus_mutex_unlock(&ws_client->ts->mutex); janus_transport_session_destroy(ws_client->ts); }
json_t *NDKHelper::getJsonFromValue(Value value) { if (value.getType() == Value::Type::MAP) { ValueMap valueMap = value.asValueMap(); json_t *jsonDict = json_object(); for (auto &element : valueMap) { json_object_set_new(jsonDict, element.first.c_str(), NDKHelper::getJsonFromValue(element.second)); } return jsonDict; } else if (value.getType() == Value::Type::VECTOR) { ValueVector valueVector = value.asValueVector(); json_t *jsonArray = json_array(); size_t sizeVector = valueVector.size(); for (unsigned int i = 0; i < sizeVector; i++) { json_array_append_new(jsonArray, NDKHelper::getJsonFromValue(valueVector.at(i))); } return jsonArray; } else if (value.getType() == Value::Type::BOOLEAN) { return json_boolean(value.asBool()); } else if (value.getType() == Value::Type::INTEGER) { return json_integer(value.asInt()); } else if (value.getType() == Value::Type::DOUBLE) { return json_real(value.asDouble()); } else if (value.getType() == Value::Type::STRING) { return json_string(value.asString().c_str()); } return NULL; }
static json_t * zeta_common_handshake_fields(zeta_client_t * zetaClient) { json_t * handshakeFields = json_object(); json_t * ext = json_object(); json_t * auth = json_object(); json_t * data = json_object(); json_object_set_new(auth, "data", data); json_object_set_new(auth, "action", json_string_nocheck("authenticate")); zeta_handshake_manager_t * hm = zetaClient->handshakeManager; char * type = cometd_malloc_fn(strlen(hm->businessId) + strlen(hm->deploymentId) + strlen(hm->authType) + 3); strcpy(type, hm->businessId); strcat(type, "."); strcat(type, hm->deploymentId); strcat(type, "."); strcat(type, hm->authType); json_object_set_new(auth, "type", json_string_nocheck(type)); json_object_set_new(auth, "resource", json_string_nocheck(zetaClient->resource)); json_object_set_new(auth, "version", json_string_nocheck("none")); json_object_set_new(ext, "authentication", auth); json_object_set_new(handshakeFields, "ext", ext); return handshakeFields; }
static void escape_slashes() { /* Test dump escaping slashes */ json_t *json; char *result; json = json_object(); json_object_set_new(json, "url", json_string("https://github.com/akheron/jansson")); result = json_dumps(json, 0); if(!result || strcmp(result, "{\"url\": \"https://github.com/akheron/jansson\"}")) fail("json_dumps failed to not escape slashes"); free(result); result = json_dumps(json, JSON_ESCAPE_SLASH); if(!result || strcmp(result, "{\"url\": \"https:\\/\\/github.com\\/akheron\\/jansson\"}")) fail("json_dumps failed to escape slashes"); free(result); json_decref(json); }
static char * build_key_post (json_t *jwk) { json_t *obj = json_object(); json_object_set_new(obj, "chipid2", json_string("1")); json_object_set_new(obj, "sub", json_string(sub)); json_object_set_new(obj, "chipid1", json_string("3")); json_object_set_new(obj, "aud", json_string("dm")); json_object_set_new(obj, "chipid3", json_string("2")); json_object_set_new(obj, "pubkey", jwk); char * jwt = jwt_encode_old (obj, ES256, hard_sign); return jwt; }
void graph_response_delNodeResponse(req_t * req, json_t * request, json_t * response, int32_t requestId, void *spss, req_store_t * req_store) { const char *ack = json_string_value(json_object_get(response, "ack")); if (strcmp(ack, "ok") == 0) { json_t *wrequest = json_object(); json_object_set_new (wrequest, "requestId", json_integer(requestId)); json_object_set(wrequest, "request", request); zmsg_t *req = zmsg_new(); char *req_str = json_dumps(wrequest, JSON_COMPACT); printf("\nbroker:spss sent: %s\n", req_str); zmsg_addstr(req, req_str); free(req_str); zmsg_send(&req, spss); json_decref(wrequest); } else { if (strcmp(ack, "fail") == 0) { // This can fail because of the existence of links // clean things up } request_store_delete(req_store, requestId); } }
/* TRP update msg */ static json_t *tr_msg_encode_trp_upd(TRP_UPD *update) { json_t *jupdate=NULL; json_t *jrecords=NULL; json_t *jrec=NULL; TRP_INFOREC *rec; if (update==NULL) return NULL; jupdate=json_object(); if (jupdate==NULL) return NULL; jrecords=json_array(); if (jrecords==NULL) { json_decref(jupdate); return NULL; } json_object_set_new(jupdate, "records", jrecords); /* jrecords now a "borrowed" reference */ for (rec=trp_upd_get_inforec(update); rec!=NULL; rec=trp_inforec_get_next(rec)) { tr_debug("tr_msg_encode_trp_upd: encoding inforec."); jrec=tr_msg_encode_inforec(rec); if (jrec==NULL) { json_decref(jupdate); /* also decs jrecords and any elements */ return NULL; } if (0!=json_array_append_new(jrecords, jrec)) { json_decref(jupdate); /* also decs jrecords and any elements */ json_decref(jrec); /* this one did not get added so dec explicitly */ return NULL; } } return jupdate; }
int OutputJSONBuffer(json_t *js, LogFileCtx *file_ctx, MemBuffer *buffer) { if (file_ctx->sensor_name) { json_object_set_new(js, "host", json_string(file_ctx->sensor_name)); } if (file_ctx->prefix) MemBufferWriteRaw(buffer, file_ctx->prefix, file_ctx->prefix_len); int r = json_dump_callback(js, MemBufferCallback, buffer, JSON_PRESERVE_ORDER|JSON_COMPACT|JSON_ENSURE_ASCII| #ifdef JSON_ESCAPE_SLASH JSON_ESCAPE_SLASH #else 0 #endif ); if (r != 0) return TM_ECODE_OK; LogFileWrite(file_ctx, buffer); return 0; }
Status loginServerOtpEnable(const Login &login, const std::string &otpToken, const long timeout) { const auto url = ABC_SERVER_ROOT "/otp/on"; JsonPtr json(json_pack("{sssssssi}", ABC_SERVER_JSON_L1_FIELD, base64Encode(login.lobby.authId()).c_str(), ABC_SERVER_JSON_LP1_FIELD, base64Encode(login.authKey()).c_str(), ABC_SERVER_JSON_OTP_SECRET_FIELD, otpToken.c_str(), ABC_SERVER_JSON_OTP_TIMEOUT, timeout)); auto key = login.lobby.otpKey(); if (key) json_object_set_new(json.get(), ABC_SERVER_JSON_OTP_FIELD, json_string(key->totp().c_str())); HttpReply reply; ABC_CHECK(AirbitzRequest().post(reply, url, json.encode())); ServerReplyJson replyJson; ABC_CHECK(replyJson.decode(reply.body)); ABC_CHECK(replyJson.ok()); return Status(); }
json_t *make_timestamp(const char* key, const char *value, const char *format, const char *replicate, baton_error_t *error) { init_baton_error(error); char *formatted = format_timestamp(value, format); json_t *result = json_pack("{s:s}", key, formatted); if (!result) { set_baton_error(error, -1, "Failed to pack timestamp '%s': '%s' as JSON", key, value); goto error; } if (replicate) { int base = 10; char *endptr; int repl = strtoul(replicate, &endptr, base); if (*endptr) { set_baton_error(error, -1, "Failed to parse replicate number from " "string '%s'", replicate); goto error; } json_object_set_new(result, JSON_REPLICATE_KEY, json_integer(repl)); } free(formatted); return result; error: if (formatted) free(formatted); return NULL; }
// sets a json value for a key int json_object_set_int(json_t *object, char *key, int *value, json_context_t *json_context) { int exit_code = 0; json_t *json_integer_value = NULL; check_not_null(object); check_not_null(key); check_not_null(json_context); if (value != NULL) { json_integer_value = json_integer(*value); check_not_null(json_integer_value); check_result(json_object_set_new(object, key, json_integer_value), 0); json_integer_value = NULL; } else { check_result(json_object_set(object, key, json_null()), 0); } goto cleanup; error: exit_code = -1; cleanup: if (json_integer_value != NULL) { json_free(json_integer_value); } return exit_code; }
int add_timestamps(json_t *object, const char *created, const char *modified, const char *replicate, baton_error_t *error) { json_t *iso_created = NULL; // Ref to be stolen by result json_t *iso_modified = NULL; // Ref to be stolen by result json_t *timestamps; init_baton_error(error); if (!json_is_object(object)) { set_baton_error(error, -1, "Failed to add timestamp data: " "target not a JSON object"); goto error; } iso_created = make_timestamp(JSON_CREATED_KEY, created, ISO8601_FORMAT, replicate, error); if (error->code != 0) goto error; iso_modified = make_timestamp(JSON_MODIFIED_KEY, modified, ISO8601_FORMAT, replicate, error); if (error->code != 0) goto error; timestamps = json_pack("[o, o]", iso_created, iso_modified); if (!timestamps) { set_baton_error(error, -1, "Failed to pack timestamp array"); goto error; } return json_object_set_new(object, JSON_TIMESTAMPS_KEY, timestamps); error: if (iso_created) json_decref(iso_created); if (iso_modified) json_decref(iso_modified); return error->code; }
static void get_user_playlists(sp_playlistcontainer *pc, struct evhttp_request *request, void *userdata) { json_t *json = json_object(); json_t *playlists = json_array(); json_object_set_new(json, "playlists", playlists); int status = HTTP_OK; for (int i = 0; i < sp_playlistcontainer_num_playlists(pc); i++) { sp_playlist *playlist = sp_playlistcontainer_playlist(pc, i); if (!sp_playlist_is_loaded(playlist)) { status = HTTP_PARTIAL; continue; } json_t *playlist_json = json_object(); playlist_to_json(playlist, playlist_json); json_array_append_new(playlists, playlist_json); } send_reply_json(request, status, status == HTTP_OK ? "OK" : "Partial Content", json); }
json_t* getSourceJson(XElement* source) { json_t* ret = json_object(); CTSTR name = source->GetName(); float x = source->GetFloat(TEXT("x")); float y = source->GetFloat(TEXT("y")); float cx = source->GetFloat(TEXT("cx")); float cy = source->GetFloat(TEXT("cy")); bool render = source->GetInt(TEXT("render")) > 0; json_object_set_new(ret, "name", json_string_wchar(name)); json_object_set_new(ret, "x", json_real(x)); json_object_set_new(ret, "y", json_real(y)); json_object_set_new(ret, "cx", json_real(cx)); json_object_set_new(ret, "cy", json_real(cy)); json_object_set_new(ret, "render", json_boolean(render)); return ret; }
int event_jansson() { printf ("产生json格式数据......\n"); json_t *objectmsg; json_t *objectall; json_t *tmp; char *result; //printf ("对象object测试...\n"); objectmsg = json_object(); objectall = json_object(); /* 得到一个json格式的字符串 */ json_object_set_new (objectmsg, "name1", json_string("value1")); json_object_set_new (objectmsg, "name2", json_string("value2")); json_t *name3 = json_string("value3"); json_t *name4 = json_string("value4"); json_object_set_new (objectmsg, "name3", name3); json_object_set_new (objectmsg, "name4", name4); result = json_dumps(objectmsg, JSON_PRESERVE_ORDER); tmp = json_string (result); free(result); result = NULL; json_object_set_new (objectall, "objectmsg", tmp); json_object_set_new (objectall, "name5", json_string("value6")); result = json_dumps(objectall, JSON_PRESERVE_ORDER); FILE *pf = fopen("str.json", "w"); fwrite(result, sizeof(char), strlen(result), pf); fclose(pf); pf = NULL; json_decref(tmp); printf("result=%s\n", result); /* 以上程序得出的json格式字符串 */ //result = "{\"objectmsg\": \"{\"name1\": \"value1\", \"name2\": \"value2\", \"name3\": \"value3\", \"name4\": \"value4\"}\", \"name5\": \"value6\"}"; free(result); json_decref(objectmsg); json_decref(objectall); }