All   Archive   Code   News   Projects  


My name is Stephen Schieberl. I live in the woods near Portland, Oregon. Hit me up to work together.

Ban the Rewind?


As much as I love to do interesting front end work, I find that most of my projects end up being "icebergs". That is, a lot of behind the scenes stuff goes on make these visualizations happen. Reading and writing JSON data is one of those critical nuts-and-bolts things in these projects. Cinder doesn't have it's own JSON parser (yet), so I wrote a Cinder-compatible JsonCpp wrapper to make my life a little easier. Download link and sample usage below. Download ciJson for Cinder ciJson 0.1.0 beta CREATE JSON To create JSON from scratch, just declare a Value object and use the ci::json append methods. When complete, you can convert the structure to a string, or save to file or even a URL. // Create JSON json::Value mData; // Add data of a few types json::append(mData, "myString", "test"); json::append(mData, "myInt", 1); json::append(mData, "myBool", true); // Add a string array vector<string> mStrings; mStrings.push_back("one"); mStrings.push_back("two"); mStrings.push_back("three"); json::append(mData, "myStringArray", mStrings); // Add an array of objects (append value to itself three times) vector<json::Value> mValues; mValues.push_back(mData); mValues.push_back(mData); mValues.push_back(mData); json::append(mData, "myObjects", mValues); // Serialize data into string string mJsonStr = json::serialize(mData); // Save to file json::save(mData, getAppPath() + "\\data.json"); // POST to URL (Windows only) json::saveUrl(mData, ""); This would output the following: { "myBool" : true, "myInt" : 1, "myObjects" : [ { "myBool" : true, "myInt" : 1, "myString" : "test", "myStringArray" : [ "one", "two", "three" ] }, { "myBool" : true, "myInt" : 1, "myString" : "test", "myStringArray" : [ "one", "two", "three" ] }, { "myBool" : true, "myInt" : 1, "myString" : "test", "myStringArray" : [ "one", "two", "three" ] } ], "myString" : "test", "myStringArray" : [ "one", "two", "three" ] } READ JSON To read JSON, you can deserialize it from an existing string, or just load it from a file or URL. Because ciJson wraps JsonCpp, you can use square bracket operators to traverse the structure, or the namespaces convenience methods. The example below reads the file we just saved. // Load file json::Value mData = json::load(getAppPath() + "\\data.json"); // json::Value mData = json::loadUrl(""); // Load from URL // Read properties with convenience methods bool mBool = json::readBool(mData, "myBool"); string mString = json::readString(mData, "myString"); vector<json::Value> mObjects = json::readValues(mData, "myObjects"); // Read properties using [] operators string mObjString = mObjects[0]["myString"].asString(); string mObjStringArrayItem = mObjects[0]["myStringArray"][1].asString(); // "two"