FAQFAQ   SearchSearch   MemberlistMemberlist   UsergroupsUsergroups   RegisterRegister 
 ProfileProfile   Log in to check your private messagesLog in to check your private messages   Log inLog in 

Announcing: CashewJSON

 
Post new topic   Reply to topic     Forum Index -> Cashew
View previous topic :: View next topic  
Author Message
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Tue Nov 28, 2006 8:15 pm    Post subject: Announcing: CashewJSON Reply with quote

I've added a new branch to Cashew for working with the JSON data format. (More information on JSON at: http://www.json.org/ )

Normal use is by importing cashew.json.value and working with the JsonValue template class. Conveniece aliases exist as JsonValueUtf*, where * is one of 8, 16, 32. Note this isn't uber-tested as yet, though my scenarios I've run it through have worked. The JSON parser also at least tries to give somewhat meaningful error messages, wrapped as exceptions for your own code to do something with if you so desire.

Example:
Code:

  import cashew .json .value ;
  import mango .io .FilePath ;

  struct Config {
    bool reverse ;
    bool showIndex ;
    char[] prefix ;

    static Config load (char[] profile) {
      Config result ;
      scope auto json = JsonValueUtf8.read(new FilePath("myapp.config"));

      with (result) {
        reverse = json[profile]["reverse"].asBool;
        showIndex = json[profile]["show index"].asBool;
        prefix = json[profile]["prefix"].asString;
      }
      return result;
    }
  }


A little contrived, but hopefully somewhat illustrative. If there is a type mismatch (calling .asBool on a JSON Array, for example) an exception is thrown.

I'll be adding a .write([FilePath]) static method for dumping JSON data as well, I promise. At least the thing works!

Also, do please take a look at the parser and let me know darn quick if it could be done better. I admit to not having a whole lot of experience in that department, which was part of why I wanted to write the thing in the first place! Best to learn on something relatively simple, I figure.
_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
petetheman



Joined: 04 Sep 2007
Posts: 1
Location: South Africa

PostPosted: Tue Sep 04, 2007 9:22 am    Post subject: Re: Announcing: CashewJSON Reply with quote

Hi
I'm trying to get the json library to work under tango, I'm new to D. I've change the imports so that they import the tango equivilant of the mango imports. I am still getting the following error.

Has anyone been able to get this to work in tango?

Here is the error which I get:
Quote:
C:\tango\bin\link.exe messageserver+configreader+list,,,cashew.lib+user32+kernel
32/noi+tango.lib;
OPTLINK (R) for Win32 Release 7.50B1
Copyright (C) Digital Mars 1989 - 2001 All Rights Reserved

messageserver.obj(messageserver)
Error 42: Symbol Undefined _D6cashew4json5value16__T9JsonValueTaZ9JsonValue4rea
dFAaZC6cashew4json5value16__T9JsonValueTaZ9JsonValue
--- errorlevel 1


I'm working with windows.

Thanks
_________________
Kind Regards
Peter
Back to top
View user's profile Send private message MSN Messenger
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Tue Sep 04, 2007 3:09 pm    Post subject: Reply with quote

The whole JSON package needs re-writing anyhow. Give me a bit.
_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Tue Sep 04, 2007 8:28 pm    Post subject: Reply with quote

Well, its been a bit. Smile There's a new CashewJSON in the repository, and it seems to work. Let me know if it does anything strange!

Here's a rewrite of that sample usage from above... its really not much different.
Code:
import cashew .json .Value ;
import tango  .io   .File  ;

struct Config {
    bool   reverse   ;
    bool   showIndex ;
    char[] prefix    ;

    static Config load (char[] profile) {
        Config result ;

        scope file = new File("myapp.config");
        scope json = JsonValue.parse(cast(char[]) file.read);

        with (result) {
            reverse   = json[profile]["reverse"   ].asBool   ;
            showIndex = json[profile]["show index"].asBool   ;
            prefix    = json[profile]["prefix"    ].asString ;
        }
        return result;
    }
}

_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
baxissimo



Joined: 23 Oct 2006
Posts: 241
Location: Tokyo, Japan

PostPosted: Thu Apr 10, 2008 6:07 am    Post subject: Re: Announcing: CashewJSON Reply with quote

csauls wrote:

I'll be adding a .write([FilePath]) static method for dumping JSON data as well, I promise. At least the thing works!


Any chance you'll be getting around to that soon?
Back to top
View user's profile Send private message
baxissimo



Joined: 23 Oct 2006
Posts: 241
Location: Tokyo, Japan

PostPosted: Thu Apr 10, 2008 9:22 am    Post subject: Doesn't compile Reply with quote

Actually, the latest version in cashew's svn doesn't compile.

First TracedException doesn't exist in my Tango (svn).

Second Tango doesn't define string,dstring,wstring aliases, but the json modules are using them.

Third, in the example above the code tries to run parse() on a char[] but there's no overload of parse for char[], only dchar[].

Finally here's a simple start of an encoder (JsonValue -> string converter):

Code:

    /+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
     +  Convert value to JSON-format string
     +/
    public dstring encode() {
        dstring escape_str(dstring s) {
            // todo escape quotes in string!
            return s;
        }

        switch (_type) {
        case JsonType.Null :
            return "null"d;
        case JsonType.Bool   :
        case JsonType.Int    :
        case JsonType.Float  :
            return asString();
        case JsonType.String :
            return "\""d ~ escape_str(asString()) ~ "\""d;
        case JsonType.Array:
        {
            if (_a.length == 0) return "[]"d;
            dstring ret = "["d;
            foreach(elem; _a) {
                ret ~= elem.encode() ~ ", "d;
            }
            ret[$-2] = ']';
            return ret[0..$-1];
        }
        case JsonType.Object:
        {
            if (_a.length == 0) return "{}"d;
            dstring ret = "{\n"d;
            foreach(key,value ; _o) {
                ret ~= "  \""d ~ escape_str(key) ~ "\" : "d ~ value.encode() ~ ",\n"d;
            }
            ret[$-2] = '}';
            return ret;
        }
        default:
            assert(false, ".encode() with unknown type");
        }
    }

Back to top
View user's profile Send private message
brad
Site Admin


Joined: 22 Feb 2004
Posts: 490
Location: Atlanta, GA USA

PostPosted: Sat May 24, 2008 9:23 pm    Post subject: Reply with quote

Here's a patch that got things shaped up for me... Note the change in the lexer for key and value tokens surrounded by quotes.

Code:

brad@Macintosh:~/dev/d/cashew$ svn diff
Index: cashew/json/Exception.d
===================================================================
--- cashew/json/Exception.d     (revision 100)
+++ cashew/json/Exception.d     (working copy)
@@ -10,10 +10,14 @@
 
 static import Int = tango .text .convert .Integer ;
 
+alias char[] string;
+alias wchar[] wstring;
+alias dchar[] dstring;
+
 /*****************************************************************************************
  *  Root class for all CashewJSON exceptions.
  */
-abstract class JsonException : TracedException {
+abstract class JsonException : Exception {
     this (char[] msg) {
         super("CashewJSON: " ~ msg);
     }
Index: cashew/json/Parser.d
===================================================================
--- cashew/json/Parser.d        (revision 100)
+++ cashew/json/Parser.d        (working copy)
@@ -18,6 +18,10 @@
     import tango .io .Stdout ;
 }
 
+alias char[] string;
+alias wchar[] wstring;
+alias dchar[] dstring;
+
 /+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  + 
  +/
@@ -278,7 +282,9 @@
                             inEsc = true;
                             continue;
                         }
-                        else if (c == '"') {
+                        else if (c == '"') {
+                            tokValue.s = buf;
+                            return TOK_STRING;
                             break;
                         }
                         else if (c == EOF) {
Index: cashew/json/Value.d
===================================================================
--- cashew/json/Value.d (revision 100)
+++ cashew/json/Value.d (working copy)
@@ -22,6 +22,10 @@
 static import Float = tango .text .convert .Float   ;
 static import Int   = tango .text .convert .Integer ;
 
+alias char[] string;
+alias wchar[] wstring;
+alias dchar[] dstring;
+
 /+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
  +  JSON Data Types
  +/

_________________
I really like the vest!
Back to top
View user's profile Send private message
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Sat May 24, 2008 9:51 pm    Post subject: Reply with quote

Thanks... Not even going to get into what was going on there with the string/wstring/dstring stuff. Let's just say I got too used to my modified libs I was running before. ^^ Meanwhile, all uses have been nixed in favor of (w/d)char[], and the files are patched.

Also, I'm working (as in literally right now) on adding the .write() feature.
_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Sat May 24, 2008 11:32 pm    Post subject: Reply with quote

Okay, and there it is. JsonValue now has a .encode() method which returns a dstring[] textdump of the data, all pretty-printed and everything. Voila, etc. Also, string escaping is there and relatively comprehensive. It escapes all the things JSON supports (\", \t, \n, etc) including extra control codes (using \u00??).

Compiled and tested on a small contrived json object just to be sure, so it ought to work out of the box. If not, blame it on me having a long day and working on this when I probably shouldn't have, slap me a couple times, then tell me what's wrong and I'll fix.
_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
baxissimo



Joined: 23 Oct 2006
Posts: 241
Location: Tokyo, Japan

PostPosted: Sun May 25, 2008 8:28 pm    Post subject: Reply with quote

csauls wrote:
Okay, and there it is. JsonValue now has a .encode() method which returns a dstring[] textdump of the data, all pretty-printed and everything. Voila, etc. Also, string escaping is there and relatively comprehensive. It escapes all the things JSON supports (\", \t, \n, etc) including extra control codes (using \u00??).

Compiled and tested on a small contrived json object just to be sure, so it ought to work out of the box. If not, blame it on me having a long day and working on this when I probably shouldn't have, slap me a couple times, then tell me what's wrong and I'll fix.


Thanks. The check in seems to use unix newlines whereas the original had dos newlines, unless I'm doing something wrong here. So the files you edited now have a mix and match of dos/unix endings.
Back to top
View user's profile Send private message
brad
Site Admin


Joined: 22 Feb 2004
Posts: 490
Location: Atlanta, GA USA

PostPosted: Sun May 25, 2008 10:15 pm    Post subject: Reply with quote

google for 'svn:eol-style'
_________________
I really like the vest!
Back to top
View user's profile Send private message
csauls



Joined: 27 Mar 2004
Posts: 278

PostPosted: Tue May 27, 2008 11:27 pm    Post subject: Reply with quote

Heh, you caught me. Not too long ago we played rock paper scissors here at the house and decided to stop using Windows, so my personal machine is running Ubuntu. I'll feed the files through a script or gedit some time to make them consistant again.
_________________
Chris Nicholson-Sauls
Back to top
View user's profile Send private message AIM Address Yahoo Messenger
Display posts from previous:   
Post new topic   Reply to topic     Forum Index -> Cashew All times are GMT - 6 Hours
Page 1 of 1

 
Jump to:  
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum


Powered by phpBB © 2001, 2005 phpBB Group