SPandya
SPandya

Reputation: 1209

Use JSON String in JavaScript

I created a JSON string using JSON.NET.

using following code

  public void JSONTable()
    {
        StringBuilder str = new StringBuilder();
        SqlConnection con = new SqlConnection("Data Source=INBDQ2WK2LBCD2S\\SQLEXPRESS;Initial Catalog=MCAS;Integrated Security=SSPI");
        SqlDataAdapter adp = new SqlDataAdapter("select top 10 x,dt from test4 order by Id desc", con);
        DataTable dt = new DataTable();
        adp.Fill(dt);

        string DATA = JsonConvert.SerializeObject(dt, new Newtonsoft.Json.Formatting());

    }

The JSON looks like

[{"x":"0","dt":"11/21/2013 3:07:53 PM"},{"x":"0","dt":"11/21/2013 3:07:52 PM"},{"x":"0","dt":"11/21/2013 3:07:50 PM"},{"x":"0","dt":"11/21/2013 2:47:21 PM"},{"x":"0","dt":"11/21/2013 2:47:20 PM"},{"x":"0","dt":"11/21/2013 2:20:02 PM"},{"x":"188","dt":"11/20/2013 11:46:53 AM"},{"x":"188","dt":"11/13/2013 11:31:38 AM"},{"x":"188","dt":"11/13/2013 11:31:26 AM"},{"x":"188","dt":"10/31/2013 2:49:27 PM"}]

Now how can I use this JSON String DATA into Javascript?

And How can I create a physical file with .json extension?

Upvotes: 0

Views: 107

Answers (2)

Anatolii Gabuza
Anatolii Gabuza

Reputation: 6260

If you have a json data stored as a string and you want to get an object in JS - use $.parseJSON(yourStringJSON) from jQuery. Another option (I prefer it) is to use JSON.parse(yourStringJSON).
Both methods return json object.

Upvotes: 1

Enam
Enam

Reputation: 1268

If you need onload object:

You may create in your code-behind global public string variable with valid JSON:

public string DATA;

After that create js variable to use it in your client code:

var jsDATA = <%= DATA %>;

If your JSON was valid no JSON.Parse is needed.

Upvotes: 1

Related Questions