How to export data from LinqPAD as JSON?

依然范特西╮ 提交于 2019-12-03 10:56:14

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".

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();
Yang C

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.

As of version 4.47, LINQPad has the ability to export JSON built in. Combined with the new lprun.exe utility, it can also satisfy your needs.

http://www.linqpad.net/lprun.aspx

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!