std::string toJSON(State &state) { std::string s; s="{ "; s+="\"grid\": ["; for (size_t y = 0; y < state.fields[0].size(); ++y) { s+="["; for (size_t x = 0; x < state.fields.size(); ++x) { if (state.fields[x][y].is<FluxCapatitor>()) s+=toJSON(state.fields[x][y].as<FluxCapatitor>()); if (state.fields[x][y].is<Doc>()) s+=toJSON(state.fields[x][y].as<Doc>()); if (state.fields[x][y].is<Chest>()) s+=toJSON(state.fields[x][y].as<Chest>()); if (state.fields[x][y].is<DeLorean>()) s+=toJSON(state.fields[x][y].as<DeLorean>()); if (state.fields[x][y].is<Capability>()) s+="{ \'elementType\" : \"capability\" }"; if (state.fields[x][y].is<boost::blank>()) s+="{ \'elementType\" : \"blank\" }"; if (state.fields[x][y].is<Wall>()) s+="{ \'elementType\" : \"wall\" }"; if(x<state.fields.size()-1) s+=","; } s+="]"; if(y<state.fields[0].size()-1) s+=","; } s+="]"; s+="}"; return s; }
static const char *GetJsonText(KonohaContext *kctx, struct JsonBuf *jsonbuf, const char *key, size_t keylen_or_zero, const char *defval) { if(key == NULL) JSONString_get(toJSON(jsonbuf->json_i)); size_t length = KeyLen(key, keylen_or_zero); return JSON_getString(toJSON(jsonbuf->json_i), key, &length); }
static kbool_t SetJsonArrayAt(KonohaContext *kctx, struct JsonBuf *jsonbuf, size_t index, struct JsonBuf *otherbuf) { if(JSON_TYPE_CHECK(Array, toJSON(jsonbuf->json_i))) { JSONArray_set(toJSON(jsonbuf->json_i), index, toJSON(otherbuf->json_i)); return true; } return false; }
static kbool_t RetrieveJsonArrayAt(KonohaContext *kctx, struct JsonBuf *jsonbuf, size_t index, struct JsonBuf *otherbuf) { if(JSON_TYPE_CHECK(Array, toJSON(jsonbuf->json_i))) { otherbuf->json_i = JSONArray_get(toJSON(jsonbuf->json_i), index).bits; return otherbuf->json_i == 0; } return false; }
void toJSON(const Generic & data, std::ostream & out) { { auto boolData = data.get<bool>(); if(boolData != nullptr) { out << (*boolData ? "true" : "false"); return; } } { auto numberData = data.get<float>(); if(numberData != nullptr) { out << *numberData; return; } } { auto stringData = data.get<std::string>(); if(stringData != nullptr) { out << '"' << Util::StringUtils::escape(*stringData) << '"'; return; } } { auto arrayData = data.get<GenericArray>(); if(arrayData != nullptr) { out << '['; bool first = true; for(const auto & element : *arrayData) { if(first) { first = false; } else { out << ","; } toJSON(element, out); } out << ']'; return; } } { auto mapData = data.get<GenericMap>(); if(mapData != nullptr) { out << '{'; bool first = true; for(const auto & element : *mapData) { if(first) { first = false; } else { out << ","; } out << '"' << Util::StringUtils::escape(element.first.toString()) << "\":"; toJSON(element.second, out); } out << '}'; return; } } }
static int64_t GetJsonInt(KonohaContext *kctx, struct JsonBuf *jsonbuf, const char *key, size_t keylen_or_zero, int64_t defval) { if(key == NULL) { if(JSON_TYPE_CHECK(Int32, toJSON(jsonbuf->json_i))) { return JSONInt_get(toJSON(jsonbuf->json_i)); } } return JSON_getInt(toJSON(jsonbuf->json_i), key, KeyLen(key, keylen_or_zero)); }
static kbool_t AppendJsonArray(KonohaContext *kctx, struct JsonBuf *jsonbuf, struct JsonBuf *otherbuf) { if(JSON_TYPE_CHECK(Array, toJSON(jsonbuf->json_i))) { JSONArray_append((JSONMemoryPool *)(PLATAPI JsonHandler), toJSON(jsonbuf->json_i), toJSON(otherbuf->json_i)); return true; } return false; }
static kbool_t SetJsonKeyValue(KonohaContext *kctx, struct JsonBuf *jsonbuf, const char *key, size_t keylen_or_zero, struct JsonBuf *otherbuf) { if(!JSON_TYPE_CHECK(Object, toJSON(jsonbuf->json_i))) { return false; } size_t keylen = KeyLen(key, keylen_or_zero); JSONObject_set((JSONMemoryPool *)(PLATAPI JsonHandler), toJSON(jsonbuf->json_i), key, keylen, toJSON(otherbuf->json_i)); return true; }
void JSONJob::execute() { std::shared_ptr<Project> proj = project(); const Path root = proj->path(); const Dependencies deps = proj->dependencies(); // error() << deps.keys(); assert(proj); const SymbolMap &map = proj->symbols(); write("{"); bool firstObject = true; for (Dependencies::const_iterator it = deps.begin(); it != deps.end(); ++it) { const Path path = Location::path(it->first); if (path.startsWith(root) && (match.isEmpty() || match.match(path))) { const Location loc(it->first, 0); const int srcRootLength = project()->path().size(); if (firstObject) { firstObject = false; } else { write(","); } write<64>("\"%s\":[", path.constData() + srcRootLength); bool firstSymbol = true; SymbolMap::const_iterator sit = map.lower_bound(loc); while (sit != map.end() && sit->first.fileId() == it->first) { Location targetLocation; SymbolInfo target = sit->second.bestTarget(map, 0, &targetLocation); const String type = sit->second.kindSpelling(); if (firstSymbol) { firstSymbol = false; } else { write(","); } if (!targetLocation.isNull()) { write<256>("{\"location\":%s,\"type\":\"%s\",\"target\":%s}", toJSON(sit->first, it->first, sit->second.symbolLength, srcRootLength).constData(), type.constData(), toJSON(targetLocation, it->first, target.symbolLength, srcRootLength).constData()); } else { write<256>("{\"location\":%s,\"type\":\"%s\"}", toJSON(sit->first, it->first, sit->second.symbolLength, srcRootLength).constData(), type.constData()); } ++sit; } write("]"); } } write("}"); }
bool Zerobuf::operator==( const Zerobuf& rhs ) const { if( this == &rhs ) return true; // not optimal, but correct and easy return toJSON() == rhs.toJSON(); }
bool OAuth10Credentials::toFile(const OAuth10Credentials& credentials, const std::string& credentialsFile) { ofJson json = toJSON(credentials); try { Poco::FileOutputStream fos(ofToDataPath(credentialsFile, true)); if (fos.good()) { fos << json; fos.close(); return true; } else { throw Poco::IOException("Bad file output stream."); } } catch (const Poco::Exception& exception) { ofLogError("Credentials::toFile") << exception.displayText(); return false; } return true; }
std::string toJSON(const MetadataNode& m) { std::ostringstream o; toJSON(m, o); return o.str(); }
String TracedLayoutObject::asTraceFormat() const { StringBuilder builder; RefPtr<JSONObject> json(toJSON()); json->writeJSON(&builder); return builder.toString(); }
std::string ApplicationDescription::toString() const { json_object * j = toJSON(); std::string s = json_object_to_json_string(j); json_object_put(j); return s; }
void FunctionWrapper::jsonExecToJSON( JSON::Entity const &arg, JSON::ArrayEncoder &resultArrayEncoder ) { JSON::Encoder jg = resultArrayEncoder.makeElement(); toJSON( jg ); }
static kbool_t SetJsonValue(KonohaContext *kctx, struct JsonBuf *jsonbuf, const char *key, size_t keylen_or_zero, KJSONTYPE type, ...) { va_list ap; va_start(ap, type); JSON val = toJSON(NewJsonI((JSONMemoryPool *)(PLATAPI JsonHandler), type, ap)); kbool_t ret = true; if(key != NULL) { size_t keylen = KeyLen(key, keylen_or_zero); JSONObject_set((JSONMemoryPool *)(PLATAPI JsonHandler), toJSON(jsonbuf->json_i), key, keylen, val); } else { jsonbuf->json_i = val.bits; } va_end(ap); return ret; }
void ProducerWrapper::jsonExecGetJSONDesc( JSON::Entity const &arg, JSON::ArrayEncoder &resultArrayEncoder ) { JSON::Encoder jg = resultArrayEncoder.makeElement(); toJSON( jg ); }
bool Database::save(const char* filename) const { auto out = FilePrintStream::open(filename, "w"); if (!out) return false; out->print(toJSON()); return true; }
bool Zerobuf::operator == ( const Zerobuf& rhs ) const { if( this == &rhs || ( !_allocator && getTypeIdentifier() == rhs.getTypeIdentifier( ))) { return true; } return toJSON() == rhs.toJSON(); }
static kbool_t IsJsonType(struct JsonBuf *jsonbuf, KJSONTYPE type) { switch(type) { case KJSON_OBJECT: return JSON_TYPE_CHECK(Object, toJSON(jsonbuf->json_i)); case KJSON_ARRAY: return JSON_TYPE_CHECK(Array , toJSON(jsonbuf->json_i)); case KJSON_STRING: return JSON_TYPE_CHECK(String, toJSON(jsonbuf->json_i)); case KJSON_INT: return JSON_TYPE_CHECK(Int32 , toJSON(jsonbuf->json_i)); case KJSON_DOUBLE: return JSON_TYPE_CHECK(Double, toJSON(jsonbuf->json_i)); case KJSON_BOOLEAN: return JSON_TYPE_CHECK(Bool , toJSON(jsonbuf->json_i)); case KJSON_NULL: return JSON_TYPE_CHECK(Null , toJSON(jsonbuf->json_i)); case KJSON_INT64: return JSON_TYPE_CHECK(Int64 , toJSON(jsonbuf->json_i)); case KJSON_LONG: return JSON_TYPE_CHECK(Int32 , toJSON(jsonbuf->json_i)); } return false; /* imf */ }
nsresult nsJSON::EncodeInternal(JSContext* cx, const JS::Value& aValue, nsJSONWriter* writer) { JSAutoRequest ar(cx); // Backward compatibility: // nsIJSON does not allow to serialize anything other than objects if (!aValue.isObject()) { return NS_ERROR_INVALID_ARG; } JS::Rooted<JSObject*> obj(cx, &aValue.toObject()); /* Backward compatibility: * Manually call toJSON if implemented by the object and check that * the result is still an object * Note: It is perfectly fine to not implement toJSON, so it is * perfectly fine for GetMethod to fail */ JS::Rooted<JS::Value> val(cx, aValue); JS::Rooted<JS::Value> toJSON(cx); if (JS_GetProperty(cx, obj, "toJSON", toJSON.address()) && toJSON.isObject() && JS_ObjectIsCallable(cx, &toJSON.toObject())) { // If toJSON is implemented, it must not throw if (!JS_CallFunctionValue(cx, obj, toJSON, 0, NULL, val.address())) { if (JS_IsExceptionPending(cx)) // passing NS_OK will throw the pending exception return NS_OK; // No exception, but still failed return NS_ERROR_FAILURE; } // Backward compatibility: // nsIJSON does not allow to serialize anything other than objects if (val.isPrimitive()) return NS_ERROR_INVALID_ARG; } // GetMethod may have thrown else if (JS_IsExceptionPending(cx)) // passing NS_OK will throw the pending exception return NS_OK; // Backward compatibility: // function shall not pass, just "plain" objects and arrays JSType type = JS_TypeOfValue(cx, val); if (type == JSTYPE_FUNCTION) return NS_ERROR_INVALID_ARG; // We're good now; try to stringify if (!JS_Stringify(cx, val.address(), NULL, JSVAL_NULL, WriteCallback, writer)) return NS_ERROR_FAILURE; return NS_OK; }
void ApplicationSettingsFile::SaveAs(File file) { var json = toJSON(); FileOutputStream *outputStream = file.createOutputStream(); outputStream->setPosition(0); JSON::writeToStream(*outputStream, json); outputStream->flush(); delete outputStream; outputStream = nullptr; }
static JSON JSONUString_new2(JSONMemoryPool *jm, const char *s, size_t len) { bool malloced; char *str; JSONString *o = (JSONString *) JSONMemoryPool_Alloc(jm, sizeof(*o), &malloced); JSON json = toJSON(ValueU(o)); JSON_Init(json); str = (len > JSONSTRING_INLINE_SIZE) ? (char *) malloc(len) : o->text; memcpy(str, s, len); JSONString_init(o, (const char *)str, len); return json; }
DataPromisePtr DirectorySharingPromise::directoryListing (const Path & path) const { String osp = osPath (path); DirectoryListing listing; Error error = sf::listDirectory(osp, &listing); if (error) { Log (LogInfo) << LOGID << "List directory of " << osp << " returned " << toString (error) << std::endl; return DataPromisePtr(); } ByteArrayPtr result = createByteArrayPtr(); *result = toJSON (listing); return sf::createDataPromise(result); }
bool Rig::save(string filename, bool overwrite) { // Test if the file already exists. ifstream ifile(filename); if (ifile.is_open() && !overwrite) { return false; } ifile.close(); ofstream rigFile; rigFile.open(filename, ios::out | ios::trunc); rigFile << toJSON().write_formatted(); return true; }
bool Database::save(const char* filename) const { auto scope = DECLARE_CATCH_SCOPE(m_vm); auto out = FilePrintStream::open(filename, "w"); if (!out) return false; String data = toJSON(); if (UNLIKELY(scope.exception())) { scope.clearException(); return false; } out->print(data); return true; }
static size_t DoJsonEach(KonohaContext *kctx, struct JsonBuf *jsonbuf, void *thunk, void (*doEach)(KonohaContext *, const char *, struct JsonBuf *, void *)) { size_t count = 0; struct JsonBuf eachbuf = {}; { JSON Key, Val; JSONObject_iterator Itr; JSON obj = toJSON(jsonbuf->json_i); JSON_OBJECT_EACH(obj, Itr, Key, Val) { const char *key = Key.str->str; eachbuf.json_i = Val.bits; doEach(kctx, key, &eachbuf, thunk); count++; } } return count; }
bool LaunchPoint::toFile() const { // NOTE: we only support persisting dynamic launchpoints at this point if (!isRemovable() || isDefault()) return false; // dynamic launch points have appinfo files named by their launchpointid's std::string filePath = Settings::LunaSettings()->lunaLaunchPointsPath; if (filePath[filePath.size()-1] != '/') filePath += "/"; filePath += launchPointId(); // persist a launch points appinfo json_object* json = toJSON(); int res = json_object_to_file((char*)filePath.c_str(), json); if (json && !is_error(json)) json_object_put(json); return res != -1; }
//-------------------------------------------------------------- void testApp::onJavascriptCallback(void* replyMsg, string url, wstring funcName, Berkelium::Script::Variant *args, size_t numArgs){ cout << "*** onJavascriptCallback at URL " << url << ", " << (replyMsg?"synchronous":"async") << endl; wcout << " Function name: " << funcName << endl; for (size_t i = 0; i < numArgs; i++) { Berkelium::WideString jsonStr = toJSON(args[i]); wcout << L" Argument " << i << ": "; if (args[i].type() == Berkelium::Script::Variant::JSSTRING) { wcout << L"(string) " << args[i].toString() << endl; } else { wcout << jsonStr << endl; } Berkelium::Script::toJSON_free(jsonStr); } if (replyMsg) { browser->window()->synchronousScriptReturn(replyMsg, numArgs ? args[0] : Berkelium::Script::Variant()); } log.push_back("*** onJavascriptCallback at URL " + url); }
bool CEnvGen::process() { if (m_showInputOnly) { if (m_displayFormat == XML_Format) { StringBuffer cfgXML; toXML(m_params, cfgXML.clear()); printf("Input as XML format:\n"); printf("%s\n\n",cfgXML.str()); } else if (m_displayFormat == JSON_Format) { StringBuffer cfgJSON; toJSON(m_params, cfgJSON.clear()); printf("Input as JSON format:\n"); printf("%s\n\n",cfgJSON.str()); } else printf("Unknown display format: %d \n\n", m_displayFormat); return true; } IPropertyTree* config = m_params->queryPropTree("Config"); const char* mode = config->queryProp("@mode"); if (!stricmp(mode, "create") ) m_iConfigEnv->create(config); else m_iConfigEnv->runUpdateTasks(config); // blindly set attribute with xpath if (m_arrXPaths.length() > 0) { unsigned nCount = 0; while (nCount < m_arrXPaths.length()) { m_iConfigEnv->setAttribute( m_arrXPaths.item(nCount).str(), m_arrAttrib.item(nCount).str(), m_arrValues.item(nCount).str() ); nCount++; } } // blindly add content with xpath if (m_arrContentXPaths.length() > 0) { unsigned nCount = 0; while (nCount < m_arrContentXPaths.length()) { int format = (!stricmp(m_arrContentFormats.item(nCount), "json")) ? JSON_Format : XML_Format; m_iConfigEnv->addContent( m_arrContentXPaths.item(nCount), m_arrContents.item(nCount), format); nCount++; } } StringBuffer out; m_iConfigEnv->getContent(NULL, out, XML_SortTags | XML_Format); Owned<IFile> pFile; const char* envFile = config->queryProp("@env-out"); //printf("output envxml to file %s\n", envFile); pFile.setown(createIFile(envFile)); Owned<IFileIO> pFileIO; pFileIO.setown(pFile->open(IFOcreaterw)); pFileIO->write(0, out.length(), out.str()); //printf("%s", out.str()); if (!m_iConfigEnv->isEnvironmentValid(out)) { fprintf(stderr, "The result environment.xml is invalid.\n"); return false; } return true; }