digitalmars.D.learn - How to check if JSONValue of type object has a key?
- Borislav Kosharov (12/12) Oct 06 2015 I'm using std.json for parsing json. I need to check if a
- via Digitalmars-d-learn (9/11) Oct 06 2015 try
- Fusxfaranto (14/26) Oct 06 2015 Additionally, just like associative arrays, if you need to access
- Marco Leise (13/26) Oct 06 2015 And you could go further and write
- Borislav Kosharov (1/1) Oct 08 2015 Thanks guys that was I was looking for!
I'm using std.json for parsing json. I need to check if a specific string key is in JSONValue.object. The first thing I tried was: JSONValue root = parseJSON(text); if(root["key"].isNull == false) { //do stuff with root["key"] } But that code doesn't work, because calling root["key"] will throw an exception of key not fount if "key" isn't there. I need some method `root.contains("key")` method to check if the object has a key. Thanks in advance!
Oct 06 2015
On Tue, Oct 06, 2015 at 08:28:46PM +0000, Borislav Kosharov via Digitalmars-d-learn wrote:JSONValue root = parseJSON(text); if(root["key"].isNull == false) {try if("key" in root) { // it is there } else { // it is not there } you can also do if("key" !in root) {}
Oct 06 2015
On Tuesday, 6 October 2015 at 20:44:30 UTC, via Digitalmars-d-learn wrote:On Tue, Oct 06, 2015 at 08:28:46PM +0000, Borislav Kosharov via Digitalmars-d-learn wrote:Additionally, just like associative arrays, if you need to access the value, you can get a pointer to it with the in operator (and if the key doesn't exist, it will return a null pointer). const(JSONValue)* p = "key" in root; if (p) { // key exists, do something with p or *p } else { // key does not exist }JSONValue root = parseJSON(text); if(root["key"].isNull == false) {try if("key" in root) { // it is there } else { // it is not there } you can also do if("key" !in root) {}
Oct 06 2015
Am Tue, 06 Oct 2015 21:39:28 +0000 schrieb Fusxfaranto <fusxfaranto gmail.com>:Additionally, just like associative arrays, if you need to access the value, you can get a pointer to it with the in operator (and if the key doesn't exist, it will return a null pointer). const(JSONValue)* p = "key" in root; if (p) { // key exists, do something with p or *p } else { // key does not exist }And you could go further and write if (auto p = "key" in root) { // key exists, do something with p or *p } else { // key does not exist } -- Marco
Oct 06 2015