Json data issue

Hi Guys,
I am returning JSON data from the server with ajax. When the data return it come like:
"['Id','Name','Phone','MailStop','Active','Out','UserName','RowTimeStamp','UserId','EmailAddress','FirstName','LastName','SSN','StatusStatus',]"

The issue I have here is the quotation in the beginning and the end. I do I remove these quotations. I have to take this data above and make it like a string.
I was trying many things like stringify, replace.
please see my code example:

function GetData() {
        var data;
        $.ajax({
            type: "GET",
            url: '/Tables/Getpaging',
            dataType: "json",
            async: false,
            //data: {},
            success: function (resp) {
                data = resp
            }
        });
        return data;
    }

    var Dataobj = GetData().BindData;

function GetHeaders() {
        var headerName = "";
        for (var i = 0; i < Dataobj.length; i++) {
            if (i == 0) {
                for (var key in Dataobj[i]) {
                    headerName += "'" + key + "',";
                }
            } else {
                break;
            }
        }
        debugger;       
        var arr = "[" + headerName + "]";
        return arr;
    }
    

Open in new window

LVL 1
Moti Mashiah.NET DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

leakim971PluritechnicianCommented:
you should fight with your server code instead trying to fix at the end, don't create issue to search solution
for your problem, at least two ways to solve on client side(...)

replace line 13 :
return data;
by (solution 1):
return eval(data); // dangerous
or by (solution 2):
return data.replace(/\[|'|,]$/g,"").split(","); // better

testing solutions
0
Julian HansenCommented:
What you have supplied is not valid JSON

1. Your items are not enclosed in double quotes
2. You have an orphan ',' at the end of the string.

As Leakim said the right call here is to change your server script to send valid JSON

This is what your JSON should look like
["Id","Name","Phone","MailStop","Active","Out","UserName","RowTimeStamp","UserId","EmailAddress","FirstName","LastName","SSN","StatusStatus"]

Open in new window

You can use this tool to validate your JSON https://jsonformatter.curiousconcept.com/
0
Moti Mashiah.NET DeveloperAuthor Commented:
First, let me respond to the first guy. Hi there Leakim971 you sound very condescending and not smart enough so please don't even try to help.  

Hi, Julian good to hear from you,

I return the right JSON from the server:
Please check this JSON data below:

Now I will explain what I want to do: I have a couple of objects that I return from the server and one of them, as you can see in my data, is "BindData" which is a list object.  Now I would like to take just the properties name from the first row:

Here is an example how I do it:
 var Dataobj = GetData().BindData;
 function GetHeaders() {
        var headerName = "";
        for (var i = 0; i < Dataobj.length; i++) {
            if (i == 0) {
                for (var key in Dataobj[i]) {
                    headerName += "'" + key + "',";
                }
            } else {
                break;
            }
        }
        debugger;       
        var arr = "[" + headerName + "]";
        return arr;
    }

Open in new window


Now as you see in my function I'm trying to put brackets around my headerName variable. why do I do that is because I want to get like that looks like: ["Id","Name","Phone","MailStop","Active","Out","UserName","RowTimeStamp","UserId","EmailAddress","FirstName","LastName","SSN","StatusStatus"]

This is all I want to do and for some reason I am getting this:
"["Id","Name","Phone","MailStop","Active","Out","UserName","RowTimeStamp","UserId","EmailAddress","FirstName","LastName","SSN","StatusStatus"]"


{"pageNum":0,"TotalPages":312,"Header":null,"RowsData":0,"properties":0,"links":null,"Total":3120,"BindData":[{"Id":17,"Name":"Deborah Adams","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,31,136],"UserId":null,"EmailAddress":null,"FirstName":"Deborah","LastName":"Adams","SSN":"","StatusStatus":"Term"},{"Id":18,"Name":"Gregory Adams","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,33,9],"UserId":null,"EmailAddress":null,"FirstName":"Gregory","LastName":"Adams","SSN":"","StatusStatus":"Active"},{"Id":19,"Name":"Lawrence Adams","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,36,28],"UserId":null,"EmailAddress":null,"FirstName":"Lawrence","LastName":"Adams","SSN":"","StatusStatus":"Term"},{"Id":20,"Name":"Rocky Adams","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,38,206],"UserId":null,"EmailAddress":null,"FirstName":"Rocky","LastName":"Adams","SSN":"","StatusStatus":"Term"},{"Id":21,"Name":"Sarah Adamson","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,39,104],"UserId":null,"EmailAddress":null,"FirstName":"Sarah","LastName":"Adamson","SSN":"","StatusStatus":"Term"},{"Id":22,"Name":"Donnie Adcock","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,31,198],"UserId":null,"EmailAddress":null,"FirstName":"Donnie","LastName":"Adcock","SSN":"","StatusStatus":"Term"},{"Id":23,"Name":"Denver Adkins","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,31,156],"UserId":null,"EmailAddress":null,"FirstName":"Denver","LastName":"Adkins","SSN":"","StatusStatus":"Term"},{"Id":24,"Name":"John Agee","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,34,133],"UserId":null,"EmailAddress":null,"FirstName":"John","LastName":"Agee","SSN":"","StatusStatus":"Term"},{"Id":25,"Name":"Arturo Aguilar","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,29,128],"UserId":null,"EmailAddress":null,"FirstName":"Arturo","LastName":"Aguilar","SSN":"","StatusStatus":"Active"},{"Id":26,"Name":"Cesar Aguilar","Phone":null,"MailStop":null,"Active":true,"Out":true,"UserName":null,"RowTimeStamp":[0,0,0,0,0,5,30,104],"UserId":null,"EmailAddress":null,"FirstName":"Cesar","LastName":"Aguilar","SSN":"","StatusStatus":"Term"}]}

Open in new window

0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

leakim971PluritechnicianCommented:
First, let me respond to the first guy. Hi there Leakim971 you sound very condescending and not smart enough


I really don't want you get it like this, my bad...
0
Julian HansenCommented:
@Moti,

I doubt Leakim was meaning to be condescending - I certainly did not interpret his post as such - he is probably the most qualified JavaScript expert on this forum. Maybe you just misunderstood his post?

Why not just do this
var headers = JSON.stringify(Object.keys(Dataobj[0]));

Open in new window

Breaking it down - your first loop is unnecessary you can get the first element of the DataObj array using Dataobj[0]

To get the keys of the object you can use Object.keys(), compatible back to IE9

Then to get the string you want just JSON.stringify it.
Example
<script>
var Dataobj = [{
	Id:'',
	Name:'',
	Phone:'',
	MailStop:'',
	Active:'',
	Out:'',
	UserName:'',
	RowTimeStamp:'',
	UserId:'',
	EmailAddress:'',
	FirstName:'',
	LastName:'',
	SSN:'',
	StatusStatus:''
},{
	Id:'',
	Name:'',
	Phone:'',
	MailStop:'',
	Active:'',
	Out:'',
	UserName:'',
	RowTimeStamp:'',
	UserId:'',
	EmailAddress:'',
	FirstName:'',
	LastName:'',
	SSN:'',
	StatusStatus:''
}];

var keys = JSON.stringify(Object.keys(x[0]));
console.log(keys);
</script>

Open in new window

Output
["Id","Name","Phone","MailStop","Active","Out","UserName","RowTimeStamp","UserId","EmailAddress","FirstName","LastName","SSN","StatusStatus"]

Open in new window

0
Moti Mashiah.NET DeveloperAuthor Commented:
HI Julian,
Maybe I misunderstood this guy, but still, it sounds like he was trying to get down on me. I am just trying to learn how to do things right but, I am not stupid.

Anyways, sorry if I misunderstood.

Thank you for your solution as always you are the best guy on this site.
Now I'm getting the header easily without looping Thx:
 var Dataobj = GetData().BindData;
    var headers = JSON.stringify(Object.keys(Dataobj[0]));

Open in new window



But still, the result comes with the quotations
"["Id","Name","Phone","MailStop","Active","Out","UserName","RowTimeStamp","UserId","EmailAddress","FirstName","LastName","SSN","StatusStatus"]"

Open in new window


can you just help with how to get rid of these quotations?

Thank you.
0
Julian HansenCommented:
I am confused - the output I posted above from the accompanying code does not have the enclosing quotes?

I am not sure where you are getting those from.

Where are you using the string where you see the additional quotes?
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Olaf DoschkeSoftware DeveloperCommented:
I think the outer double quotes must come in somewhere else. Are you looking at some debugger showing variables and their values? Then the outer double quotes might just denote string delimiters in the display of the variable,not really being part of the variable value.
Debuggers show it that way to make a difference about strings and other data types, which is more important and apparent, if something looks like a number or date but indeed is a string.

The code you used and Julian gave you both don't add the outer string delimiters. I don't think they play a role. Simply try to alert(arr) before return arr and you should see the outer delimiters are really not part of the arr variable.

What clearly does become an unwanted part of your list is the last comma, as you add headers with headerName += "'" + key + "',"; you always have a comma after each element, which gives you one too much at the end. In such situations building up lists I typically do the inverse, putting commas in front: headerName += ",'" + key + "'"; - that means first have the commas, then the items. That moves the one too much comma at the start, where it's easier to get rid off as aftermath by substring(1), for you: var arr = "[" + headerName.substring(1) + "]" ;

substring(1) is making use of the optional end parameter of it, you just specify you want all of the string except the first (index 0) comma, so this starts copying the string at index 1 (2nd character and all further) to the end. It's a typical solution to creating comma separated value lists not only in JavaScript.

Edit: But forget about that, as JSON.stringify is much much simpler to get to the correct result.

Bye, Olaf.
0
Moti Mashiah.NET DeveloperAuthor Commented:
Hi Julian,
I used your code at it was perfect but still i got these "" "" so I just took the stringify away and it helps me to get your out put.

Here is the final solution:
 var Dataobj = GetData(pageNumber).BindData;
    var headers = Object.keys(Dataobj[0]);

instead:
var Dataobj = GetData(pageNumber).BindData;
var headers = JSON.stringify(Object.keys(Dataobj[0]));
0
Julian HansenCommented:
I see, I think the requirement was muddled somewhere but glad you are sorted.
1
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.