I have a String like this :
var str = [sa_user{username=pankaj123, userType=dataentry}, sa_user{username=data, userType=dataentry}, sa_user{username=PANKAJ, userType=parcel}, sa_user{username=davender, userType=parcel}, sa_user{username=delhiparcel, userType=dataentry}, sa_user{username=devender, userType=dataentry}, sa_user{username=amit123, userType=dataentry}, sa_user{username=sanjay, userType=dataentry}, sa_user{username=MUKESH, userType=dataentry}, sa_user{username=test, userType=dataentry}, sa_user{username=vijaykumar, userType=dataentry}, sa_user{username=puran123, userType=dataentry}, sa_user{username=sanjaykumar, userType=dataentry}, sa_user{username=nelsonanthony, userType=dataentry}, sa_user{username=ishan, userType=dataentry}, sa_user{username=manoj, userType=parcel}, sa_user{username=ranjeet, userType=dataentry}, sa_user{username=DEEPAK, userType=dataentry}, sa_user{username=ASHISH, userType=dataentry}, sa_user{username=arjun, userType=dataentry}]
I want to convert the given into JSon Object or any other data-type to access every Object variables username and usertype.
Since, the String is not in the valid form to convert into JSon Object, then how can I access the variables?
2 Answers 2
You need to parse the string, convert it to a valid json string and then in javascript you can do something like this to get the object:
var myJsonString = ""; // your json string
var obj = JSON.parse(myJsonString);
EDIT: Just put together a jsfiddle with a solution, it could be better, but it gets the job done for your specific case.
your json string should look like this to parse.
var strJson = "[
{'username':'pankaj123', 'userType':'dataentry'},
{'username':'data', 'userType':'dataentry'},
{'username':'PANKAJ', userType':parcel'},
....
]";
now solve what to do with your current string to make it like this.
strbe enclosed in quotes?jsonstring at server, can't you convert to json string usingJavaScriptSerializer(in .netframework if you are using that) before sending to client ?