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": "" }] } ]"
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" }] } ]'
Your JSON object itself is an array:
alert( jsonObject[0].user[0].Gender );
See an example at http://jsfiddle.net/GTLX3/
Related
I would like to ask for a help with reading JSON format from a device in Node-Red. I succesfully made to read the JSON content in Python, but applying the same strategy in Node-Red does not yield a success.
I tried several approches.
Use JSON node, it reports
Unexpected token in JSON at position 0
I tried the function node
var str = JSON.stringify(msg.payload);
var data = JSON.parse(str);
// var Temp1 = data["Monitor"]["S"]["S1"]["item1"]["value"];
msg.payload = data["Monitor"]["S"]["S1"]["item1"]["value"];
return msg, data;
And Node-red reports:
> TypeError: Cannot read properties of undefined (reading 'S')
To read the Json from the device I use HTTP get
{
"Monitor": {
"DeviceInfo": {
"DeviceName": "TCW241",
"HostName": "TCW241",
"ID": "5C:32:C5:00:9E:C2",
"FwVer": "TCW241-v1.240",
"MnfInfo": "www.teracomsystems.com",
"SysContact": "Petr",
"SysName": "Garaze Relay",
"SysLocation": "Garaze Anglie"
},
"S": {
"S1": {
"description": "Garaz",
"id": "28245C75D0013C29",
"item1": {
"value": "9.4",
"unit": "°C",
"alarm": "0",
"min": "-40.0",
"max": "85.0",
"hys": "8.5"
},
"item2": {
"value": "---",
"unit": "---",
"alarm": "0",
"min": "---",
"max": "---",
"hys": "---"...
DLL used: Newtonsoft.Json.Linq
When I convert another jason using below converter code it is working fine. but when i am converting given below jason getting error "{"Cannot add a nested relation or an element column to a table containing a SimpleContent column."}". If I replace the 1st seat to seat1 than it is working fine. But I cannot change anything on JSON as this response is shared by 3rd party operator.
Note : I cannot change anything on JSON.
Code:
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim xmlDoc As New XmlDocument
Dim objDS As DataSet
xmlDoc = CType(JsonConvert.DeserializeXmlNode("{""DT"": {" & jsonString.Trim().TrimStart("{").TrimEnd("}") & "} }"), XmlDocument)
objDS = New DataSet()
objDS.ReadXml(New XmlNodeReader(xmlDoc))
JSON:
{
"status":"success",
"msg":"",
"data":{
"block_key":"76570415041123",
"block_time":"7",
"ticket_detail":{
"msrtc":{
"reservation_charge":"5.0",
"asn_amount":"1.0",
"ac_service_charges":"0.0"
},
"upsrtc":"NA",
"hrtc":"NA",
"rsrtc":"NA"
},
"total_fare":280,
"base_fare":274,
"operator_commission_rate":"4.45",
"agent_commission_rate":"85",
"commission_without_gst":8.78,
"agent_tds_value":0.44,
"agent_net_commission":8.34,
"transaction_amount":271.66,
"test":{
"testing":{
"tripchild_con":"Y",
"post_passanger":[
{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
}
],
"value":{
"title":"Mr",
"name":"Ram",
"age":"70",
"sex":"M",
"birth":"0",
"seat_no":"45",
"subtotal":"280.0",
"total":"280",
"is_ladies":"false",
"mobile":"9579597539",
"email":"ram#gmail.com",
"id_type":null,
"id_number":null,
"name_on_id":null,
"primary":"True",
"ac":"false",
"sleeper":"false"
},
"senior_citizen_flag":"0",
"seats":{
"seats":[
"2",
"5",
"6",
"9",
"10",
"13",
"14",
"15",
"16",
"17",
"18",
"20",
"21",
"22",
"23",
"24",
"25",
"26",
"27",
"28",
"31",
"32",
"33",
"34",
"35",
"37",
"38",
"39",
"40",
"41",
"42",
"45"
],
"service_id":"724351",
"fare":"280.0",
"childFare":"145.0",
"seniorcitizenfare":"145.0"
},
"passengerDetails":"seniorfare else casse",
"adultFare seniorfare else casse":"274.0",
"tickets_total_basic_fare":274,
"adultFare":null
}
}
}
}
I think that Json structure cannot create Dataset.
So you have to process the data yourself and create it.
see source below
Dim jsonString = System.IO.File.ReadAllText("D:\Json.txt")
Dim dto As TestDTO
dto = JsonConvert.DeserializeObject(Of TestDTO)(jsonString)
MsgBox(dto.status)
Class TestDTO
Property status As String
Property msg As String
Property data As dataDTO
End Class
Class dataDTO
Property block_key As String
Property ticket_detail As ticketdetailDTO
End Class
Class ticketdetailDTO
Property reservation_charge As String
End Class
Below is my JSON output received post the HttpGet successful execution.
{
"results": [{
"id": "1310760",
"type": "page",
"status": "current",
"title": "UniversalProfile Release Test",
"extensions": {
"position": 9
},
"_links": {
"webui": "/display/ds/UniversalProfile+Release+Test",
"tinyui": "/x/KAAU",
"self": "http:1310760"
},
"_expandable": {
"container": "/rest/api/space/ds",
"metadata": "",
"operations": "",
"children": "/rest/api/content/1310760/child",
"history": "/rest/api/content/1310760/history",
"ancestors": "",
"body": "",
"version": "",
"descendants": "/rest/api/content/1310760/descendant",
"space": "/rest/api/space/ds"
}
}],
"start": 0,
"limit": 25,
"size": 1,
"_links": {
"self": "UniversalProfile+Release+Test",
"base": "https://alim4azad.atlassian.net/wiki",
"context": "/wiki"
}
}
I am trying to extract the value for "id" but have been unsuccessful so far.
If your JSON is in the variable output in Javascript, it'd be :
output.results[0]["id"]
Like console.log(output.results[0]["id"]).
Your results section contains arrays. You want the first (0), and then the key id.
Looking at that resulting JSON hurts my brain.
Assuming you are using JavaScript, try this: output.results[0]['id']
Try This:
JSONObject jsonObject = new JSONObject(data);
JSONArray jsonArray = jsonObject.getJSONArray("results");
JSONObject jsonObject1 = jsonArray.getJSONObject(0).getString("id");
Finally i found a solution for it . Below is the solution.
JSONArray results = getbodyPage.getJSONArray("results");
JSONObject first = results.getJSONObject(0);
Long id = first.getLong("id"); // Get id of the found page
System.out.println("INFO : Found ID - " + id);
Thank you all for your valuable inputs.
This is the json object I am working with
{
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
}
I want this as another key-value pair :
"collegeId": {
"eventno": "6062",
"eventdesc": "abc"
};
I tried concat but that gave me the result with || symbol and I cdnt iterate. I used spilt but that removes only commas.
concattedjson = JSON.stringify(JSON.parse(json1).concat(JSON.parse(json2)));
How do I add a key pair value to an existing json object ?
I am working in javascript.
This is the easiest way and it's working to me.
var testJson = {
"name": "John Smith",
"age": 32,
"employed": true,
"address": {
"street": "701 First Ave.",
"city": "Sunnyvale, CA 95125",
"country": "United States"
},
"children": [
{
"name": "Richard",
"age": 7
},
{
"name": "Susan",
"age": 4
},
{
"name": "James",
"age": 3
}
]
};
testJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
Just convert the JSON string to an object using JSON.parse() and then add the property. If you need it back into a string, do JSON.stringify().
BTW, there's no such thing as a JSON object. There are objects, and there are JSON strings that represent those objects.
You need to make an object at reference "collegeId", and then for that object, make two more key value pairs there like this:
var concattedjson = JSON.parse(json1);
concattedjson["collegeId"] = {};
concattedjson["collegeId"]["eventno"] = "6062";
concattedjson["collegeId"]["eventdesc"] = "abc";
Assuming that concattedjson is your json object. If you only have a string representation you will need to parse it first before you extend it.
Edit
demo for those who think this will not work.
const newTestJson = JSON.parse(JSON.stringify(testJson));
newTestJson.collegeId = {"eventno": "6062","eventdesc": "abc"};
testJson = newTestJson;
i know its very simple thing but i m stucked on it
i have json variable with data as follow
var jsonText =
'[ { "user": [ { "Gender": "M", "Minage": "19", "Maxage": "30", "MaritalStatusId":"0", }]
},
{ "user":[ { "maritialtype": "Does not matter" }]
},
{ "user": [ { "Value": "No" }]
} ]';
var jsonObject = JSON.parse(jsonText);
now i can access gender as jsonObject[0].user[0].Gender
but i'm not able to access maritialtype and Value
For maritialtype:
jsonObject[1].user[0].maritialtype
For Value:
jsonObject[2].user[0].Value
Because you have an array of three objects, user, which is an array or one object. It's kind of a weird structure.