bool parse_json(ConnectionInfo& info, const json& j) { try { GET_NODE_ENUM(j, "type", ConnectionType, info.Type); GET_NODE_ENUM(j, "channel", RC_CHANNEL, info.Channel); GET_NODE_STRING(j, "dev_sn", info.DevSN, RC_MAX_SN_LEN); bool ret = true; switch(info.Type) { case CT_SERIAL: ret = parse_json(info.Serial, j["info"]); break; case CT_TCPC: ret = parse_json(info.TCPClient, j["info"]); break; case CT_UDP: ret = parse_json(info.UDP, j["info"]); break; case CT_TCPS: ret = parse_json(info.TCPServer, j["info"]); break; case CT_PLUGIN: ret = parse_json(info.Plugin, j["info"]); break; case CT_TEST: default: break; } return ret; } catch (...) { return false; } }
json_t *json_loads(const char *string, json_error_t *error) { lex_t lex; json_t *result; string_data_t stream_data = { .data = string, .pos = 0 }; if(lex_init(&lex, string_get, string_eof, (void *)&stream_data)) return NULL; result = parse_json(&lex, error); if(!result) goto out; lex_scan(&lex, error); if(lex.token != TOKEN_EOF) { error_set(error, &lex, "end of file expected"); json_decref(result); result = NULL; } out: lex_close(&lex); return result; } json_t *json_loadf(FILE *input, json_error_t *error) { lex_t lex; json_t *result; if(lex_init(&lex, (get_func)fgetc, (eof_func)feof, input)) return NULL; result = parse_json(&lex, error); if(!result) goto out; lex_scan(&lex, error); if(lex.token != TOKEN_EOF) { error_set(error, &lex, "end of file expected"); json_decref(result); result = NULL; } out: lex_close(&lex); return result; }
static void test_request(const char *json) { jsmntok_t tokens[32]; int parsed = parse_json( tokens, LGTD_ARRAY_SIZE(tokens), json, strlen(json) ); bool ok; struct lgtd_jsonrpc_request req = TEST_REQUEST_INITIALIZER; struct lgtd_client client = { .io = NULL, .current_request = &req, .json = json }; ok = lgtd_jsonrpc_check_and_extract_request(&req, tokens, parsed, json); if (!ok) { errx(1, "can't parse request"); } lgtd_jsonrpc_check_and_call_set_light_from_hsbk(&client); if (set_light_called) { errx(1, "lgtd_proto_power_off was called"); } reset_client_write_buf(); }
json_t *json_loads(const char *string, json_error_t *error) { lex_t lex; json_t *result; string_data_t stream_data = { /*.data = */string, /*.pos = */0 }; if(lex_init(&lex, string_get, string_eof, (void *)&stream_data)) return NULL; result = parse_json(&lex, error); if(!result) goto out; lex_scan(&lex, error); if(lex.token != TOKEN_EOF) { error_set(error, &lex, "end of file expected"); json_decref(result); result = NULL; } out: lex_close(&lex); return result; }
int main(int argc, char* argv[]) { char* buffer; size_t length, body_pos; struct artist_album_state state = {0}; int i; setlocale(LC_ALL, ""); install_sighandler(); httpreq(&buffer, &length); body_pos = http_body_offset(buffer, length); LOG(LOG_OK, "New relases:"); parse_json(buffer + body_pos, length - body_pos, (void*)&state, artist_album_cb); for (i = 0; i < state.result_index; i++) { printf("%d. %s\n", i, state.result[i]); } spotify_main_loop(argv[1], argv[2], spotify_callback); free(buffer); for (i = 0; i < state.result_index; i++) { free(state.result[i]); } return 0; }
void benchmarkFile(char *filename) { clock_t begin, end; double time_spent; json_token *tokens = calloc(sizeof(json_token), 3000000); json_parser parser; json_parser_init(&parser); parser.tokens = tokens; parser.maxTokens = 3000000; parser_from_file(&parser, filename); begin = clock(); /* parse the json document */ parse_json(&parser, RFC4627); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printResults(&parser, filename, time_spent); file_parser_free(&parser); free(tokens); }
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error) { lex_t lex; const char *source; json_t *result; if(input == stdin) source = "<stdin>"; else source = "<stream>"; jsonp_error_init(error, source); if (input == NULL) { error_set(error, NULL, "wrong arguments"); return NULL; } if(lex_init(&lex, (get_func)fgetc, input)) return NULL; result = parse_json(&lex, flags, error); lex_close(&lex); return result; }
static void do_notify(struct ovs_cmdl_context *ctx) { struct jsonrpc_msg *msg; struct jsonrpc *rpc; struct json *params; struct stream *stream; const char *method; char *string; int error; method = ctx->argv[2]; params = parse_json(ctx->argv[3]); msg = jsonrpc_create_notify(method, params); string = jsonrpc_msg_is_valid(msg); if (string) { ovs_fatal(0, "not a JSON RPC-valid notification: %s", string); } error = stream_open_block(jsonrpc_stream_open(ctx->argv[1], &stream, DSCP_DEFAULT), &stream); if (error) { ovs_fatal(error, "could not open \"%s\"", ctx->argv[1]); } rpc = jsonrpc_open(stream); error = jsonrpc_send_block(rpc, msg); if (error) { ovs_fatal(error, "could not send notification"); } jsonrpc_close(rpc); }
int main(int argc, char **argv) { if(argc < 3) { fprintf(stderr, "%s out.db file1.json file2.json ... fileN.json\n", argv[0]); return 0; } struct cdb_make cdbm; int fd; fd = open("tmp.db", O_RDWR | O_CREAT, 0644); cdb_make_start(&cdbm, fd); argv++; argc--; char *dbname = *argv; argv++; argc--; int i; for(i = 0; i < argc; i++) { parse_json(&cdbm, argv[0]); argv++; } cdb_make_finish(&cdbm); rename("tmp.db", dbname); close(fd); return 0; }
static int8_t on_post_messages_request(int8_t cid, GSwifi::GSREQUESTSTATE state) { while (! gs.bufferEmpty()) { char letter = gs.bufferGet(); parse_json( letter ); } if (state == GSwifi::GSREQUESTSTATE_RECEIVED) { // should be xmitting or idle (xmit finished) if (IrCtrl.state == IR_WRITING) { HTTPLOG_PRINTLN("!E7"); // invalid json gs.writeHead(cid, 400); gs.writeEnd(); } else { gs.writeHead(cid, 200); gs.writeEnd(); } ring_put( &commands, COMMAND_CLOSE ); ring_put( &commands, cid ); #ifdef USE_INTERNET TIMER_START( suspend_polling_timer, SUSPEND_GET_MESSAGES_INTERVAL ); #endif } return 0; }
int main(void) { jsmntok_t tokens[32]; memset(tokens, 0, sizeof(tokens)); const char json[] = "[[\"*\"],[1,2,3,4]]"; int parsed = parse_json( tokens, LGTD_ARRAY_SIZE(tokens), json, sizeof(json) ); struct lgtd_jsonrpc_target_args { const jsmntok_t *target; int target_ntokens; const jsmntok_t *label; } params = { NULL, 0, NULL }; static const struct lgtd_jsonrpc_node schema[] = { LGTD_JSONRPC_NODE( "target", offsetof(struct lgtd_jsonrpc_target_args, target), offsetof(struct lgtd_jsonrpc_target_args, target_ntokens), lgtd_jsonrpc_type_string_number_or_array, false ), LGTD_JSONRPC_NODE( "label", offsetof(struct lgtd_jsonrpc_target_args, label), -1, // this must dereference json from the what's in the token (see // next comment): lgtd_jsonrpc_type_number, false ) };
/* Parses the given JSON File * Returns * - 0 on success and all the arguments will be pointing to parsed data * - 1 on failure and garbage elsewhere */ int parse_json_file(const char *filename, int *arg_c, int *live, char *user, char *group, char *command) { int fd; /* file descriptor */ int r = 1; /* result (default, failure) */ char json_str[FILE_SIZE+10]; /* file content store */ /* slurp the file contents */ fd = open(filename, R_OK); if (fd == -1) { _LOGGER("(ERROR) Cannot Open File [%s] Reason [%s]", filename, strerror(errno)); return 1; } r = read(fd, json_str, FILE_SIZE); /* i should use stat to see file size, this is a possible overflow */ if (r <= 0 || r >= FILE_SIZE) { _LOGGER("File size for file (%s) unexpected expected size (Expected Size:%d)", filename, FILE_SIZE); return 1; } json_str[r] = '\0'; /* more efficient than bzero :-) */ close(fd); r = parse_json(json_str, arg_c, live, user, group, command); return r; }
json_t *json_load_callback(json_load_callback_t callback, void *arg, size_t flags, json_error_t *error) { lex_t lex; json_t *result; callback_data_t stream_data; memset(&stream_data, 0, sizeof(stream_data)); stream_data.callback = callback; stream_data.arg = arg; jsonp_error_init(error, "<callback>"); if (callback == NULL) { error_set(error, NULL, "wrong arguments"); return NULL; } if(lex_init(&lex, (get_func)callback_get, &stream_data)) return NULL; result = parse_json(&lex, flags, error); lex_close(&lex); return result; }
json_t *json_loadf(FILE *input, size_t flags, json_error_t *error) { lex_t lex; const char *source; json_t *result; (void)flags; /* unused */ if(lex_init(&lex, (get_func)fgetc, input)) return NULL; if(input == stdin) source = "<stdin>"; else source = "<stream>"; jsonp_error_init(error, source); result = parse_json(&lex, error); if(!result) goto out; lex_scan(&lex, error); if(lex.token != TOKEN_EOF) { error_set(error, &lex, "end of file expected"); json_decref(result); result = NULL; } out: lex_close(&lex); return result; }
int main(void) { jsmntok_t tokens[32]; const char json[] = ("{" "\"jsonrpc\": \"2.0\"," "\"method\": \"power_off\"," "\"params\": {\"target\": \"*\"}," "\"id\": \"42\"" "}"); int parsed = parse_json( tokens, LGTD_ARRAY_SIZE(tokens), json, sizeof(json) ); bool ok; struct lgtd_jsonrpc_request req = TEST_REQUEST_INITIALIZER; struct lgtd_client client = { .io = NULL, .current_request = &req, .json = json }; ok = lgtd_jsonrpc_check_and_extract_request(&req, tokens, parsed, json); if (!ok) { errx(1, "can't parse request"); } lgtd_jsonrpc_check_and_call_power_off(&client); if (!power_off_called) { errx(1, "lgtd_proto_power_off wasn't called"); } return 0; }
static int save_json(const struct mg_str *data, const char *file_name) { FILE *fp; int len = parse_json(data->p, data->len, NULL, 0); if (len <= 0) { LOG(LL_ERROR, ("%s\n", "Invalid JSON string")); return 0; } fp = fopen("tmp", "w"); if (fp == NULL) { LOG(LL_ERROR, ("Error opening file for writing\n")); return 0; } if (fwrite(data->p, 1, len, fp) != (size_t) len) { LOG(LL_ERROR, ("Error writing file\n")); fclose(fp); return 0; } if (fclose(fp) != 0) { LOG(LL_ERROR, ("Error closing file\n")); return 0; } if (rename("tmp", file_name) != 0) { LOG(LL_ERROR, ("Error renaming file to %s\n", file_name)); return 0; } return 1; }
json_t *json_loadb(const char *buffer, size_t buflen, size_t flags, json_error_t *error) { lex_t lex; json_t *result; buffer_data_t stream_data; jsonp_error_init(error, "<buffer>"); if (buffer == NULL) { error_set(error, NULL, "wrong arguments"); return NULL; } stream_data.data = buffer; stream_data.pos = 0; stream_data.len = buflen; if(lex_init(&lex, buffer_get, (void *)&stream_data)) return NULL; result = parse_json(&lex, flags, error); lex_close(&lex); return result; }
json_t *json_loads(const char *string, size_t flags, json_error_t *error) { lex_t lex; json_t *result; string_data_t stream_data = {string, 0}; (void)flags; /* unused */ if(lex_init(&lex, string_get, (void *)&stream_data)) return NULL; jsonp_error_init(error, "<string>"); result = parse_json(&lex, error); if(!result) goto out; lex_scan(&lex, error); if(lex.token != TOKEN_EOF) { error_set(error, &lex, "end of file expected"); json_decref(result); result = NULL; } out: lex_close(&lex); return result; }
/*可以根据用户的要求获取某地的天气信息,如输入“大连”或“dalian”,可以查询大连的天气信息 *该函数获取一天的信息。 *get_weather_all_city2()可以获取六天的天气信息。main函数中直接调用这两个函数即可得到天气信息。 */ void get_weather_all_city() { char city_name[MAX]; memset(&city_name, 0, sizeof(city_name)); printf("Input city name:"); fgets(city_name, MAX, stdin); //printf("weather:%s \n", city_name); city_name[strlen(city_name) - 1] = '\0'; char *city_name1 = (char *)malloc(MAX); strcpy(city_name1, city_name); //printf("city_name1: %s\n", city_name1); //char *file_name = (char *)malloc(MAX); char *file_name = strcat(city_name1, ".cache"); //printf(" filename:%s\n", file_name); char *city_id_json = http_request(city_name, "/search?cityname=", "61.4.185.213", 80); //printf("%s\n",city_id_json); char *cityid; cityid = extract_city_id(city_id_json); char *ss = strcat(cityid, ".html"); char *city_weather_info = http_request(ss, "/data/cityinfo/", "61.4.185.201", 80); //char *city_weather_info = http_request(ss, "/data/", "113.108.239.118 ", 80); //or IP:113.108.239.107 //printf("city_weather_info\n%s\n", city_weather_info); char *city_weather_json = extract_weather_json(city_weather_info, 8); //printf("city_weather_json\n%s\n",city_weather_json); char *weather = parse_json(city_weather_json); printf("%s\n", weather); }
void plugin_options::parse_json(std::string path) { // first try to open as a directory osd_directory *directory = osd_opendir(path.c_str()); if (directory != nullptr) { // iterate over all files in the directory for (const osd_directory_entry *entry = osd_readdir(directory); entry != nullptr; entry = osd_readdir(directory)) { if (entry->type == ENTTYPE_FILE) { std::string name = entry->name; if (name == "plugin.json") { std::string curfile = std::string(path).append(PATH_SEPARATOR).append(entry->name); std::ifstream ifs(curfile); rapidjson::IStreamWrapper isw(ifs); rapidjson::Document document; document.ParseStream<0>(isw); if (document.HasParseError()) { std::string error(GetParseError_En(document.GetParseError())); osd_printf_error("Unable to parse plugin definition file %s. Errors returned:\n", curfile.c_str()); osd_printf_error("%s\n", error.c_str()); return; } if (document["plugin"].IsObject()) { std::string name = document["plugin"]["name"].GetString(); std::string description = document["plugin"]["description"].GetString(); std::string type = document["plugin"]["type"].GetString(); bool start = false; if (document["plugin"].HasMember("start") && (std::string(document["plugin"]["start"].GetString()) == "true")) start = true; if (type=="plugin") { add_entry(core_strdup(name.c_str()),core_strdup(description.c_str()), OPTION_BOOLEAN, start ? "1" : "0"); } } } } else if (entry->type == ENTTYPE_DIR) { std::string name = entry->name; if (!(name == "." || name == "..")) { parse_json(path + PATH_SEPARATOR + name); } } } // close the directory and be done osd_closedir(directory); } }
int32_t iio_ioctl_json(void *dev_handle, uint32_t opcode, char *injson, char **outjson, void *ctx_out, uint32_t flags) { struct iio_device *device = (struct iio_device *)dev_handle; struct qnio_msg *msg = NULL; struct iovec data, out; kvset_t *inps = NULL; kvset_t *outps = NULL; qnio_stream *stream = NULL; int err; if (injson != NULL) { inps = parse_json(injson); if(inps == NULL) { nioDbg("Parse json failed"); return -1; } } msg = iio_message_alloc(&apictx->msg_pool); msg->hinfo.opcode = opcode; msg->hinfo.data_type = DATA_TYPE_PS; msg->hinfo.payload_size = 0; data.iov_len = 0; if (inps != NULL) { msg->send = new_io_vector(1, NULL); data.iov_base = kvset_marshal(inps, (int *)&(data.iov_len)); io_vector_pushback(msg->send, data); kvset_free(inps); } msg->recv = NULL; msg->hinfo.payload_size = data.iov_len; safe_strncpy(msg->hinfo.target, device->devid, NAME_SZ64); msg->user_ctx = ctx_out; msg->hinfo.flags = QNIO_FLAG_REQ_NEED_RESP; err = iio_msg_submit(device, msg, flags); if (err) { iio_message_free(msg); } else if(!(flags & IIO_FLAG_ASYNC)) { err = iio_msg_wait(msg); if(err == 0) { if (msg->recv) { out = io_vector_at(msg->recv, 0); stream = new_qnio_stream(0); kvset_unmarshal(out.iov_base, &outps); kvset_print(stream, 0, outps); *outjson = (char *) malloc(stream->size + 1); memcpy(*outjson, stream->buffer, stream->size); ((char *)*outjson)[stream->size] = '\0'; qnio_delete_stream(stream); kvset_free(outps); } } iio_message_free(msg); } return err; }
/** * @name process_repl_commands: */ void process_repl_commands(gammu_state_t **s, FILE *stream) { for (;;) { boolean_t is_eof = FALSE; char *line = read_line(stream, &is_eof); if (!line) { break; } if (is_eof && line[0] == '\0') { goto cleanup; } parsed_json_t *p = parse_json(line); if (p) { char **argv = NULL; int argc = 0, err = 0; boolean_t rv = parsed_json_to_arguments(p, &argc, &argv, &err); if (!rv) { print_json_validation_error(err); goto cleanup_json; } int result = 0; if (!process_command(s, argc, argv, &result)) { if (!result) { print_usage_error(U_ERR_CMD_INVAL); } goto cleanup_json; } } else { print_json_validation_error(V_ERR_PARSE); } cleanup_json: if (p) { release_parsed_json(p); } cleanup: free(line); if (is_eof) { break; } } }
GssAdaptive * gss_adaptive_load (GssServer * server, const char *key, const char *dir, const char *version, GssDrmType drm_type, GssAdaptiveStream stream_type) { GssAdaptive *adaptive; char *filename; gboolean ret; GError *error = NULL; JsonParser *parser; g_return_val_if_fail (GSS_IS_SERVER (server), NULL); g_return_val_if_fail (key != NULL, NULL); g_return_val_if_fail (dir != NULL, NULL); GST_DEBUG ("looking for %s", key); parser = json_parser_new (); filename = g_strdup_printf ("%s/gss-manifest", dir); ret = json_parser_load_from_file (parser, filename, &error); if (!ret) { GST_DEBUG ("failed to open %s", filename); g_free (filename); g_object_unref (parser); g_error_free (error); return NULL; } g_free (filename); GST_DEBUG ("loading %s", key); adaptive = gss_adaptive_new (); adaptive->server = server; adaptive->content_id = g_strdup (key); adaptive->kid = create_key_id (key); adaptive->kid_len = 16; adaptive->drm_type = drm_type; adaptive->stream_type = stream_type; gss_playready_generate_key (server->playready, adaptive->content_key, adaptive->kid, adaptive->kid_len); ret = parse_json (adaptive, parser, dir, version); if (!ret) { gss_adaptive_free (adaptive); g_object_unref (parser); GST_WARNING ("json format error in %s/gss-manifest", dir); return NULL; } g_object_unref (parser); GST_DEBUG ("loading done"); return adaptive; }
static void test_float(const char *json) { jsmntok_t tokens[8]; parse_json(tokens, LGTD_ARRAY_SIZE(tokens), json, strlen(json)); if (!lgtd_jsonrpc_type_float_between_0_and_1(&tokens[1], json)) { errx(1, "%s wasn't considered as a valid float >= 0 and <= 1", json); } }
static GVariant * parse_json_tuple (JsonNode *node, const GVariantType *child_type, GError **error) { GVariant *result = NULL; GPtrArray *children; GVariant *value; JsonArray *array; guint length; guint i; children = g_ptr_array_new (); if (!check_type (node, JSON_NODE_ARRAY, 0, error)) goto out; array = json_node_get_array (node); length = json_array_get_length (array); for (i = 0; i < length; i++) { value = NULL; if (child_type == NULL) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Too many values in tuple/struct"); } else { value = parse_json (json_array_get_element (array, i), child_type, error); } if (!value) goto out; g_ptr_array_add (children, value); child_type = g_variant_type_next (child_type); } if (child_type) { g_set_error (error, G_IO_ERROR, G_IO_ERROR_INVALID_DATA, "Too few values in tuple/struct"); goto out; } result = g_variant_new_tuple ((GVariant *const *)children->pdata, children->len); children->len = 0; out: g_ptr_array_foreach (children, (GFunc)g_variant_unref, NULL); g_ptr_array_free (children, TRUE); return result; }
static int8_t on_get_messages_response(int8_t cid, uint16_t status_code, GSwifi::GSREQUESTSTATE state) { HTTPLOG_PRINT(P("< G /m ")); HTTPLOG_PRINTLN(status_code); if (status_code != 200) { gs.bufferClear(); } switch (status_code) { case 200: while (! gs.bufferEmpty()) { char letter = gs.bufferGet(); parse_json( letter ); } if (state == GSwifi::GSREQUESTSTATE_RECEIVED) { // should not be WRITING here, should be XMITTING or IDLE (xmit finished) if (IrCtrl.state == IR_WRITING) { // prevent from locking in WRITING state forever IR_state( IR_IDLE ); } ring_put( &commands, COMMAND_CLOSE ); ring_put( &commands, cid ); if ((polling_cid == cid) || (polling_cid == CID_UNDEFINED)) { polling_cid = CID_UNDEFINED; ring_put( &commands, COMMAND_START_POLLING ); } // if polling_cid != cid // there's already an ongoing polling request, so request again when that one finishes } break; case HTTP_STATUSCODE_CLIENT_TIMEOUT: polling_cid = CID_UNDEFINED; ring_put( &commands, COMMAND_CLOSE ); ring_put( &commands, cid ); irkit_httpclient_start_polling( 5 ); break; case HTTP_STATUSCODE_DISCONNECT: polling_cid = CID_UNDEFINED; irkit_httpclient_start_polling( 5 ); break; // heroku responds with 503 if longer than 30sec, // or when deploy occurs case 503: default: if (state == GSwifi::GSREQUESTSTATE_RECEIVED) { ring_put( &commands, COMMAND_CLOSE ); ring_put( &commands, cid ); irkit_httpclient_start_polling( 5 ); } break; } return 0; }
Json::Value& DiscordCommunicator::get_config() { Json::Value config_root; std::string errs; parse_json(saveybot::Communicator::config_file_name, &config_root, &errs); __json_config = config_root["discord"]; return __json_config; }
// 'do it all' function bool parse_json( const std::string &filename, message_handlert &message_handler, jsont &dest) { std::ifstream in(filename); if(!in) return true; return parse_json(in, filename, message_handler, dest); }
tmx_map* tmx_load(const char *path) { tmx_map *map = NULL; const char *extension; FILE *file; int fchar; if (!tmx_alloc_func) tmx_alloc_func = realloc; if (!tmx_free_func) tmx_free_func = free; /* is 'path' a JSON or a XML file ? */ extension = strrchr(path, '.'); /* First using the file extension */ if (extension && (!strcmp(extension, ".tmx") || !strcmp(extension, ".xml"))) { map = parse_xml(path); } else if (extension && !strcmp(extension, ".json")) { map = parse_json(path); } else { /* open the file and check with the first character */ if ((file = fopen(path, "r"))) { fchar = fgetc(file); fclose(file); if (fchar == '<') { map = parse_xml(path); } else if (fchar == '{') { map = parse_json(path); } else { tmx_errno = E_FORMAT; } } else { if (errno == EACCES) { tmx_errno = E_ACCESS; } else if (errno == ENOENT) { tmx_errno = E_NOENT; } else { tmx_err(E_UNKN, "%s", strerror(errno)); } } } return map; }
int main(int argc,char *argv[]) { int i; char json[32768], buffer[32768]; if (argc < 2) { puts("Usage: ./a.out [ga|gd|gv]"); exit(1); } read(STDIN_FILENO, buffer, 32768); request_and_response(argv[1], buffer, json); /* parse and print result in same format as other clients */ parse_json(json); return 0; }