0

I am using JSON in Javascript for first time in my project of asp.net. I am new to it. I have successfully created a JSON string on page load and stored it in a hidden field. Now, in Javascript when I try to eval or parse that string, it do not parse it.

Please help. Here's how I'm doing it:

var jsonText = $("#hiddenJson").val();

var jsonObject = JSON.parse(jsonText);       

//var jsonObject = eval("(" + jsonText + ")");

alert(jsonObject.user[0].Gender);

//---- alert gives [object Object]

//------- value of jsonText is

"[ { "user": [ { "Gender": "M", "Minage": "28", "Maxage": "24", "MaritalStatusId": "2,3", "ChildrenPreferencesId": "0", "PersonalValueId": "1", "MinHeight": "6", "MaxHeight": "1", "BodyTypeId": "0", "ComplexionId": "0", "HealthAttributeId": "1", "SpecialCaseId": "1", "ReligionId": "3,5", "CasteId": "1,6", "MotherTongueId": "", "QualificationLevelId": "2,3", "QualificationFieldId": "", "WorkingWithId": "4,5", "ProfessionArea": "3,4", "WorkingAsId": "3,4", "IncomeId": "3", "DietId": "0", "SmokeId": "1", "DrinkId": "2", "CountryId": "4,5", "ResidencyId": "", "PartnerDescription": "" }] } ]"
3
  • It's printing that because the Gender field is an object, not a string (or anything it can evaluate to a readable string). We would need the structure definition of Gender to assist further. Commented Dec 6, 2011 at 18:15
  • This is valid JSON, what is the error you are getting while trying to parse it? Commented Dec 6, 2011 at 18:45
  • Please refrain from reposting your questions. If you have details to add, edit the original question instead. Commented Dec 7, 2011 at 0:34

2 Answers 2

5

if you're using double quotes for the members of the json object, then put the whole string in single quotes instead, like

var jsonText = '[ { "user": [ { "Gender": "M", "Minage": "28", "Maxage": "24", "MaritalStatusId": "2,3", "ChildrenPreferencesId": "0", "PersonalValueId": "1", "MinHeight": "6", "MaxHeight": "1", "BodyTypeId": "0", "ComplexionId": "0", "SpecialCaseId": "1", "ReligionId": "3,5" }] } ]'
Sign up to request clarification or add additional context in comments.

Comments

2

Your JSON object itself is an array:

alert( jsonObject[0].user[0].Gender );

See an example at http://jsfiddle.net/GTLX3/

Comments

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.