Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to export data from LinqPAD as JSON?

Tags:

json

linqpad

I want to create a JSON file for use as part of a simple web prototyping exercise. LinqPAD is perfect for accessing the data from my DB in just the shape I need, however I cannot get it out as JSON very easily.

I don't really care what the schema is, because I can adapt my JavaScript to work with whatever is returned.

Is this possible?

like image 622
Drew Noakes Avatar asked Jul 11 '13 19:07

Drew Noakes


3 Answers

A more fluent solution is to add the following methods to the "My Extensions" File in Linqpad:

public static String DumpJson<T>(this T obj)
{
    return
        obj
        .ToJson()
        .Dump();
}

public static String ToJson<T>(this T obj)
{
    return
        new System.Web.Script.Serialization.JavaScriptSerializer()
        .Serialize(obj);
}

Then you can use them like this in any query you like:

Enumerable.Range(1, 10)
.Select(i =>
    new
    {
        Index = i,
        IndexTimesTen = i * 10,
    })
.DumpJson();

I added "ToJson" separately so it can be used in with "Expessions".

like image 66
DaveShaw Avatar answered Oct 12 '22 01:10

DaveShaw


This is not directly supported, and I have opened a feature request here. Vote for it if you would also find this useful.

A workaround for now is to do the following:

  • Set the language to C# Statement(s)
  • Add an assembly reference (press F4) to System.Web.Extensions.dll
  • In the same dialog, add a namespace import to System.Web.Script.Serialization
  • Use code like the following to dump out your query as JSON
new JavaScriptSerializer().Serialize(query).Dump();
like image 11
Drew Noakes Avatar answered Oct 12 '22 01:10

Drew Noakes


There's a solution with Json.NET since it does indented formatting, and renders Json dates properly. Add Json.NET from NuGet, and refer to Newtonsoft.Json.dll to your “My Extensions” query and as well the following code :

public static object DumpJson(this object value, string description = null)
{
    return GetJson(value).Dump(description);
}

private static object GetJson(object value)
{
    object dump = value;

    var strValue = value as string;
    if (strValue != null)
    {
        var obj = JsonConvert.DeserializeObject(strValue);
        dump = JsonConvert.SerializeObject(obj, Newtonsoft.Json.Formatting.Indented);
    }
    else
    {
        dump = JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented);
    }

    return dump;
}

Use .DumpJson() as .Dump() to render the result. It's possible to override more .DumpJson() with different signatures if necessary.

like image 10
Yang C Avatar answered Oct 12 '22 02:10

Yang C