2

I need to store a set of values which I get from my C# code to a javascript array. Im getting an error .. Can someone tell what the error is ? Im using this jcode.

 $.get('Dataextract.aspx', function (data, textStatus) {
        alert('Status is ' + textStatus);//success
        alert('JSON data string is: ' + data);//string as below

    var JSONdata = data;
    eval(JSONdata);//error here-> expected ;
    alert(JSONdata.rowval[0].CustomerID);

}, 'text');

I am using an ajax query to retrieve an array of JSON object. the data objects value that i get is something like this as string.

{"rowval" :[{"CustomerID":12"Title":"Mr.""FirstName":"Johnny""MiddleName":"A.""LastName":"Caprio""CompanyName":"Bikes and Motorbikes""RowNumber":10},{"CustomerID":16"Title":"Mr.""FirstName":"Christopher""MiddleName":"R.""LastName":"Beck""CompanyName":"Bulk Discount Store""RowNumber":11},{"CustomerID":18"Title":"Mr.""FirstName":"David""MiddleName":"J.""LastName":"Liu""CompanyName":"Catalog Store""RowNumber":12},{"CustomerID":19"Title":"Mr.""FirstName":"John""MiddleName":"A.""LastName":"Beaver""CompanyName":"Center Cycle Shop""RowNumber":13},{"CustomerID":20"Title":"Ms.""FirstName":"Jean""MiddleName":"P.""LastName":"Handley""CompanyName":"Central Discount Store""RowNumber":14},{"CustomerID":21"Title":"FirstName":"Jinghao""MiddleName":"LastName":"Liu""CompanyName":"Chic Department Stores""RowNumber":15},{"CustomerID":22"Title":"Ms.""FirstName":"Linda""MiddleName":"E.""LastName":"Burnett""CompanyName":"Travel Systems""RowNumber":16},{"CustomerID":23"Title":"Mr.""FirstName":"Kerim""MiddleName":"LastName":"Hanif""CompanyName":"Bike World""RowNumber":17},{"CustomerID":24"Title":"Mr.""FirstName":"Kevin""MiddleName":"LastName":"Liu""CompanyName":"Eastside Department Store""RowNumber":18},{"CustomerID":25"Title":"Mr.""FirstName":"Donald""MiddleName":"L.""LastName":"Blanton""CompanyName":"Coalition Bike Company""RowNumber":19},{"CustomerID":28"Title":"Ms.""FirstName":"Jackie""MiddleName":"E.""LastName":"Blackwell""CompanyName":"Commuter Bicycle Store""RowNumber":20}]}

Here is my C# code that is generating the JSON

sb.Append("{\"rowval\" :");
            sb.Append("[");
            if (table != null)
            {
                foreach (DataRow row in table.Rows)
                {
                    sb.Append("{");
                    if (row.Table != null && row.Table.Columns != null && row.Table.Columns.Count > 0)
                    {
                        foreach (DataColumn column in row.Table.Columns)
                        {
                            parseMember(row[column], column.ColumnName, sb);
                        }
                    }
                    sb.Append("},");
                }
            }
            sb.Append("]");
            sb.Append("}");

            sqlcon.Close();
            Response.Write(sb);



        }

        private static void parseMember(object val, string memberName, StringBuilder sb)
        {
            Type t = val.GetType();

            if (memberName != null && memberName.Trim().Length > 0)
                sb.AppendFormat("\"{0}\":", memberName);
            if (typeof(string) == t || typeof(char) == t)
                sb.AppendFormat("\"{0}\"", val.ToString());
            else
                sb.AppendFormat("{0}", val.ToString());
        }
3
  • Can you edit and post the C# code you're using to create the (faulty) JSON object? Look at the quotation marks, with spaces, and you'll see that they're mismatched: "CustomerID":"25" Title":" "Mr." "FirstName":" "Donald""... Commented Jan 17, 2012 at 15:47
  • yeah sorry . posted the wrong json.. have corrected Commented Jan 17, 2012 at 15:48
  • ^ was manually editing the wrong json that why there were errors left.. have copy pasted the json now. do see Commented Jan 17, 2012 at 16:13

2 Answers 2

2

if you are getting json then specifying dataType equal to json as 4th argument in$.getwill parse the json which you can iterate using theeach` method of jquery, like

 $.get('Dataextract.aspx', function (data, textStatus) {
        alert('Status is ' + textStatus);//success
        alert('JSON data string is: ' + data);//string as below
    // no need for eval
   // var JSONdata = data;
   // eval(JSONdata);//error here-> expected ;
    alert(JSONdata.rowval[0].CustomerID);

}, "json"); // <-- 

or you can parse the json explicitly like

 $.get('Dataextract.aspx', function (data, textStatus) {
        alert('Status is ' + textStatus);//success
        alert('JSON data string is: ' + data);//string as below

    var JSONdata = $.parseJSON(data);
   // eval(JSONdata);//error here-> expected ;  again no need for the eval
    alert(JSONdata.rowval[0].CustomerID);

}, 'text');

update

the json you are forming is not correct, for validating your json you can visit www.jsonlint.com, this is the valid json

{
    "rowval": [
        {
            "CustomerID": 12,  // <-- you are missing the commas 
            "Title": "Mr.",
            "FirstName": "Johnny",
            "MiddleName": "A.",
            "LastName": "Caprio",
            "CompanyName": "Bikes and Motorbikes",
            "RowNumber": 10
        }
    ]
}
Sign up to request clarification or add additional context in comments.

4 Comments

+1. Of course this still will only work if the JSON is properly formed.
now the error is expected - } :P json has been updated above
@KshitijBanerjee the json formed is not valid, see the answer update
Thanks! i was definitely missing that in my convertor! will update about this soon
0

You need two classes -call them RoVal and Customer, for example- and define them as so:

class RowVal
{

    public List<Customer> Customers {get;set;}
}

class Customer
{
   public int ID {get;set;}
   public string Title{get;set;}
   public string FirstName {get;set;}
   //and so on

}

Now you can deserialize that JSON string as so

JavascriptSerializer serializer = new JavascriptSerializer();
RowVal rowVal =    serializer.Deserialize<RowVal>(yourJSonstring);

2 Comments

I have to develop my application in asp 1.1 which does not have javascriptserializer
The use JSON.NET if it's possible (I don't know if JSON.NET is supported on 1.1). You should have tagged your question accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.