1

I have got below JSON response from my ASPX page back to my client page. Now I want to read the values from it and want to generate the HTML

jsonData ={ "tnf": { "ci": [ {"atit": "Australia Pass", "img": "\/fr\/english\/Images\/EN_Fly_to_Rio_de_Janeiro_v1_185_tcm233-658117.jpg", "sop": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx" } ],  "elt": [ {"t": "sfp", "value": "More special fares" } ],  "f": [ { "a": [ {"c": "Hamburg", "p": "from GBP 469*", "pm": "id=744431#744431", "t": "sfp" }, {"c": "Dubai", "p": "from GBP 559*", "pm": "id=744432#744432", "t": "sfp" }, {"c": "Thiruvananthapuram", "p": "from GBP 559*", "pm": "id=744433#744433", "t": "sfp" }, {"c": "Johannesburg", "p": "from GBP 559*", "pm": "id=744434#744434", "t": "sfp" }, {"c": "Beijing", "p": "from GBP 1,780*", "pm": "id=744435#744435", "t": "sfp" }, {"c": "Guangzhou", "p": "from GBP 469", "pm": "pub=\/fr\/english&pageurl=\/IBE.aspx&section=IBE&TID=SB&resultby=2&j=f&showpage=true&seldcity1=LHR&selacity1=JNB&selddate1=08%20Dec%2011&seladate1=09%20Dec%2011&bsp=Special+Fares+Widget&selcabinclass=0&showsearch=true", "t": "ffp" }, {"c": "Manila", "p": "from GBP 559*", "pm": "id=744437#744437", "t": "sfp" }, {"c": "Kuala Lumpur", "p": "from GBP 559*", "pm": "id=744438#744438", "t": "sfp" } ],  "d": [ {"t": "sfp", "value": "From London Heathrow (LHR)" } ] } ],  "nof": [ { "a": [ {"class": "bodyLink", "href": "\/sn\/english\/destinations_offers\/special_offers\/special_offers.aspx", "title": "Special Offers", "value": "Special Offers" } ],  "value": [ "We don’t have any Special Fares at the moment. Please check again another time, or see our current", "." ] } ], "tc": "Conditions apply for each fare.  Dublin commence from  9th January 2012.",  "u": [ {"ffp": "\/SessionHandler.aspx", "ffpm": "pageurl=\/IBE.aspx&pub=\/fr\/english&section=IBE&j=f&bsp=Special+Fares+Widget", "ot": "\/fr\/english\/destinations_offers\/special_offers\/mysite_visit_australia_pass\/mysite_visit_australia_pass.aspx", "sfp": "\/fr\/english\/destinations_offers\/special_offers\/special_fares\/special_fares.aspx" } ] }}

Please suggest how can I read it show that I can easily add it to my HTMLs

EDIT:

This the Jquery code which I am using to get these values:

$(document).ready(function() {
        $('#btnSearch').click(function() {

            var strInput = "";
            var strSearchType = $('#ddnSearchType').val();
            strInput = strInput + "?q=" + strSearchType;
            var serviceReq = "http://localhost:2853/jsonproxy/jsonprxy.aspx";

            $.ajax({
                url: serviceReq + strInput,
                dataType: "jsonp",
                jsonpCallback: "processJsonData",
                success: function(data, textStatus, jqXHR) {
                    // don't do anything here, since the processing happened in callback function
                },
                error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
            });
        });
        function processJsonData(data) {
            alert(data);
            $.each(data, function(i, tnf) {
                alert(tnf.nof[0].a[0].href)
                alert(tnf.elt[0].value)
                alert(tnf.f[0].a.c);
                $.each(tnf.f[0].a, function(j, adata) {
                    alert(adata.c);
                    alert(adata.pm)
                });

            });
        }
    });

I can see three GET variables in the HTTPFox tool,

q   even
callback    processJsonData
_   1326530518049

Its giving parser error as well as "processJsonData" function is not recognized.

and the result which is returned back from my CS is as above.

Below is code which I am using to get the JSON

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Xml;
using System.IO;
using System.Runtime.Serialization.Json;

public partial class jsonProxy : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string strResult = "";
        string strSearch = "";
        try
        {
            if (Request.QueryString.Count != 0 && Request.QueryString["q"] != string.Empty)
            {
                strSearch = Request.QueryString["q"];
            }
            strResult = performSearch(strSearch);
        }
        catch
        {
            strResult = performSearch("");
        }
        Response.Clear(); //optional: if we've sent anything before
        Response.ContentType = "text/html"; //must be 'text/xml'
        Response.ContentEncoding = System.Text.Encoding.UTF8; //we'd like UTF-8

        Response.Write("jsonData =" + strResult + "");
        Response.End(); //optional: will end processing

    }
    private string performSearch(string strSearch)
    {
       string returnStr = "";
        XmlDocument docXml = new XmlDocument();
        docXml.Load("xml/SpecialFares.xml");
        returnStr = XmlToJson.XmlToJSON(docXml);
        return (returnStr);
    }
}

Thanks

Best Regards, MS

Manoj Singh
  • 7,569
  • 34
  • 119
  • 198
  • It would be helpful if you show a sample of your desired HTML output, including the elements which might trigger a request for this JSON. – Jake Feasel Jan 14 '12 at 06:52
  • The HTML is not yet decided, I would like to have all the data in HTML TR and TD. My main objective is how can I read all the values of JSON object – Manoj Singh Jan 14 '12 at 06:58

3 Answers3

2

What you've got there isn't JSON, but javascript. To use this, you want to add a:

<script src="myscript.js" ></script>

to your html. Then jsonData will be a global object, so you can simply refer to:

alert(jsonData.tnf.ci[0].atit)

which will alert Australia Pass.

More likely, what you want to do is to remove the jsonData= part of the returned string. Then you can handle the data with a typical jQuery ajax request:

$.ajax({
  url: "your_js_url.aspx",
  dataType: "json",
  success: function(data, textStatus, jqXHR) {
    // process the js object data that will contain your returned data
    },
  error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});

More details can be found on jQuery's ajax documentation: http://api.jquery.com/jQuery.ajax/

To understand the difference between json and jsonp, Wikipedia JSONP to the rescue:

Requests for JSONP retrieve not JSON, but arbitrary JavaScript code. They are evaluated by the JavaScript interpreter, not parsed by a JSON parser.

This StackOverflow question also addresses it: What is JSONP all about?.

So with JSON, one returns the raw data in JSON format, while with JSONP one returns a script that will be evaluated by the browser's javascript interpreter. What one generally does is to make a function call in the script. In your case, you might have your apsx page return:

processJsonData( { { /*your json data here*/ } } );

The thing is, JSON data is valid Javascript notation, which is why JSON and Javascript play together so nicely.

Now, in your code you need to implement the processJsonData function:

function processJsonData(data) { ... }

Note that for this to work with jQuery, you need to change your ajax call:

$.ajax({
  url: "your_js_url.aspx",
  dataType: "jsonp",
  jsonpCallback: "processJsonData",
  success: function(data, textStatus, jqXHR) {
    // don't do anything here, since the processing happened in callback function
  },
  error: function(jqXHR, textStatus, errorThrown) { alert(textStatus); }
});

Now as to how to process the data in your processJsonData function, well, you're receiving your data as a javascript object, and how you map that to HTML depends on the data and how you want it to appear. I'm afraid your json is a little too complex for me to be able to guess what you're wanting to do with it.

To call the processJsonData function with your data, change your .cs line:

    Response.Write("jsonData =" + strResult + "");

to:

    Response.Write("processJsonData(" + strResult + ");");
Community
  • 1
  • 1
craigmj
  • 4,827
  • 2
  • 18
  • 22
  • thanks...I am trying to implementing this using JSONP as because of cross domain issue in my implementation, so above results is just an output from my aspx page, would appreciate if you can tell how can I implement JSONP and one question why this is javascript not a JSON? – Manoj Singh Jan 14 '12 at 07:06
  • How to the looping in it as alert(jsonData.tnf.ci[0].atit) is working for one only. – Manoj Singh Jan 14 '12 at 07:11
  • JSON is a data format, javascript is a programming language. So the `jsonData = ` part is setting a javascript variable. I'll edit the answer to explain jsonp. – craigmj Jan 14 '12 at 08:10
  • ok...thanks for explaining JSONP, can you please tell me what changes do I need to do in aspx.cs which is returning the JSON. I cannot see the callback in GET, and also what need to be written in function "processJsonData" – Manoj Singh Jan 14 '12 at 08:30
  • I have edited my question, I have added my CS code as well the Jquery code from which I am trying to get the values. – Manoj Singh Jan 14 '12 at 08:52
  • Have added a code change to return a jsonP callback to the processJsonData function. You will need to write that function. The `data` parameter is just a js object: you can walk it as you would any js object. – craigmj Jan 14 '12 at 09:06
  • let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/6717/discussion-between-m-s-and-craigmj) – Manoj Singh Jan 14 '12 at 09:09
0

Recommend you look into jQuery .getJson or .ajax.

But as a sample:

$.ajax({
    url: 'url/to/get/json',
    type: "Post",
    success: function (result) {
       //result will contain your json object
       //loop through json and output as HTML
});
Jack Marchetti
  • 15,536
  • 14
  • 81
  • 117
  • I know above code to be called for JSONP, I am looking how can I make the loop to my JSONData and then further add it according to my HTML – Manoj Singh Jan 14 '12 at 07:10
0

Please make sure you have added a callback function which defined in js to your JSONP script tag.

For example:

jQuery.getJSON("http://www.yourdomain.com/jsonp/ticker?symbol=IBM&callback=?", 
function(data) {//here is the parser
    alert("Symbol: " + data.symbol + ", Price: " + data.price);
});

Then in your server side script you need to do as following(java servlet)

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) 
throws ServletException, IOException {
    String jsonData = getDataAsJson(req.getParameter("symbol"));
    String output = req.getParameter("callback") + "(" + jsonData + ");";

    resp.setContentType("text/javascript");

    PrintWriter out = resp.getWriter();
    out.println(output);
}

Actually the server side script's main purpose is to return a string like "callback(obj)" than need to be execute in JS.

JSONP is used to by pass XHR cross-origin that need to include serverside script. Make sure you have already added the callback to your JSONP script. Here are Resources in IBM develperworks.

BTW: You can have a try JSON2 and JSON2-source in your callback function to make sure the returned is JSON.

And then write the parser/replacer function yourself.

Gran
  • 326
  • 1
  • 8