Save/load data to a file (JSON for phobos)

nobody somebody at somewhere.com
Tue Nov 18 08:57:26 PST 2008


"Alan Knowles" <alan at akbkhome.com> wrote in message 
news:4922079E.3080401 at akbkhome.com...
> This should work, although I really need to rewrite some of it to use 
> streams.
> http://www.akbkhome.com/svn/D_Stuff/json.d
>
>
>
>
> nobody wrote:
>> "Christopher Wright" <dhasenan at gmail.com> wrote in message 
>> news:gfpsdt$2uhd$1 at digitalmars.com...
>>> nobody wrote:
>>>> I would like to be able to save and load a lot of data to/from a file. 
>>>> (in D1)
>>>> For example a struct like this:
>>>>
>>>> struct Fruit
>>>> {
>>>>     int banana;
>>>>     double[][] orange;
>>>>     bool[] apple;
>>>> }
>>>>
>>>> Practically all the examples that I've come across only deal with 
>>>> saving and loading text, so I'm having a hard time dealing with 
>>>> saving/loading arrays/floats/bools/etc.
>>>>
>>>> What would be a good way to do this?
>>> XML is commonly used, and while I don't particularly like it, I find 
>>> it's still a reasonable choice in many circumstances.
>>>
>>> If you're using Tango, you can check out tango.text.xml.Document, which 
>>> will let you construct an XML document, and tango.text.xml.DocPrinter, 
>>> which will let you get the textual representation of such a document.
>>>
>>> In phobos, there's std.xml, which should offer equivalent functionality, 
>>> but I haven't used it.
>>
>> Unfortunately I'm using phobos, and I think std.xml is only for D2.0.
>>
>> Is there no similar for D1.0?

Hmm, I'm clearly doing something wrong because I can't get it to properly 
save doubles/reals..

void main() {

  struct A
  {
   char[] sval = "test";
   bool bval = true;
   int ival = 3;
   double dval = 4f/3;
   real rval = 8f/3;
  }

  A a;

  auto x = jsonO();
  //x.add("key1",a.sval);
  //x.add("key2",a.bval);
  x.add("key3",a.ival);
  x.add("key4",jsonV(a.dval));
  x.add("key5",jsonV(a.rval));

  auto encoded = x.encode();

  std.file.write("test.dat",encoded);

  ubyte[] file = cast(ubyte[])std.file.read("test.dat");

  auto decoded = jsonDecode(file);

  //writefln(decoded.getN("key1"));
  //writefln(decoded.getN("key2"));
  writefln(decoded.getN("key3"));
  writefln(decoded.getN("key4"));
  writefln(decoded.getN("key5"));

}

This writes to file: {"key3":3,"key4":1,"key5":2}
So the double & real seem to be converted to int.

What am I doing wrong? 




More information about the Digitalmars-d-learn mailing list