I have json data in the following format
{"updates":
{"message" :"[[student:123]] is present."},
"references":[{"type":"student","full_name":"XYZ","id":123}]
}
How can I map the student name to the message using the id present over the message?
I am relatively new to JSON parsing. I am currently using EJS template to manipulate the JSON into HTML.
In that just using
<%alert(updates.message.student)%>
returns "undefined". Please help.
updates.message is a string, not a JavaScript object. You can tell by the quotes around the whole attribute. JavaScript strings don't have a student property, so you are getting undefined. You can parse out the JSON part from the string with regular expressions and then use JSON.parse() to get the JSON object. However, the student id is also in updates.references[0].id in your example.
To get the student ID, do this:
<% alert(updates.references[0].id) %>
edit: If you are really want to get the id out of the message, you need to parse it out somehow. If the message format will always be the same, you can try a regular expression or string splitting to get the part containing the id.
var id_part = json.updates.message.split(" ")[0];
//parse out just the ID number in a group
var re = /\[\[[^:]+:(\d+)\]\]/;
var matches = re.exec(id_part);
var id = matches[1];
To then get the corresponding data out of the references part, you need to loop through until you find one with the id from the message. This would work.
//Ghetto old for loop for browser compatibility
for (var i = 0; i < updates.references.length; i++) {
if (updates.references[i].id == id) {
//We have found the reference we want.
//Do stuff with that reference.
break;
}
}
try
var json = {
"updates": {
"message": "[[student:123]] is present."
},
"references": [
{
"type": "student",
"full_name": "XYZ",
"id": 123
}
]
};
alert(json.references[0].full_name);
Related
I am trying to pull out the value "533"
{
"d": {
"ItemValue_1": 533
},
"ts": "2021-01-20T10:59:41.958591"
}
This does not work
var ItemValue_1 = msg.payload.ItemValue_1;
msg.payload = ItemValue_1;
return msg;
My result is unsuccessful
I was able to solve on my own, it works.
sensorMeasurement=JSON.parse(msg.payload);
msg.payload=sensorMeasurement.d;
var msgout = {payload : msg.payload.ItemValue_1}
return msgout;
The better way to do this is as follows:
Add a JSON node before the function node, this will turn a string payload in to a JSON object (assuming the string actually represents a JSON object).
Then if you are using a function node the following:
msg.payload = msg.payload.d.ItemValue_1;
return msg;
It is bad practice to create a new object as you did in your answer as it throws away any meta data that may be required later that is attached to the original object.
Rather than use a function node it would also be cleaner to use a change node and the Move mode to shift the msg.payload.d.ItemValue_1 to msg.payload
This should be simple.
I am getting a json response in POSTMAN and need to search through it, and if I find an name in there, set an variable based on the id # of the object that contained that name :)
{ "jsonrpc": "2.0","result":[{"id": 396,"name": "LAB",},{ "id": 404,"name":"Networks",}],"id": 1}
etc...
So, if I need to find out the id of LAB, how to go about it?
Here we go:
its simple: iterate the json object and check if name is lab then print id
var x = { "jsonrpc": "2.0","result":[{"id": 396,"name": "LAB",},{ "id": 404,"name":"Networks",}],"id": 1}
x.result.forEach(function(value, index){
if(value["name"] == "LAB"){
console.log(value["id"]);
}
})
result is:
396
I have the following JSON (simplified / minimized to show only pertinent parts) returned from a web service:
{
"results": [{
"paramName": "OutputPolyline",
"dataType": "String",
"value": "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
}],
"messages": []
}
I use the following code to parse the JSON and grab the value of the "value" key:
JObject obj = JObject.Parse(json);
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
Console.WriteLine(token.Path + " -> " + token);
The above code returns the entire value string as expected, like such "#{\"hasM\":true,\"paths\":[[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]}"
Building on the above code, how do I get only the value of the paths key? In this example, return only [[[135.24,246.13,null],[135.24,246.13,null] ... [135.24,246.13,null]]]
You cannot extract the path values from the root object via a single JsonPath query since the value of the value property is just a string literal that happens itself to be re-serialized JSON. It needs to be extracted and recursively parsed as JSON after first trimming off the # character, and Json.NET has no built-in query operator to do that as of the current version, 9.0.1.
Thus you need to do something like:
JToken token = obj.SelectToken("$.results[?(#.paramName == 'OutputPolyline')]['value']");
var paths = JToken.Parse(token.ToString().Trim('#')).SelectToken("paths");
Sample fiddle.
I have a web service that returns a serialized JSON data string. An example of what is returned is:
{"Campus":"BMSB","Program":null,"Selected":"false","Status":"NEW","Status2":null ,"Status3":null,"StudentID":00000,"StudentFirstName":"Ioneu0027a","StudendMiddle Name":"","StudentLastName":"Byra"},
{"Campus":"BMFW","Program":"Accounting- Diploma","Selected":"false","Status":"GRAD","Status2":"GRAD","Status3":null,"StudentID":00000,"StudentFirstName":"Kathryn","StudendMiddleName":"I","StudentLastName":"Eib"}
two sets of the same data seperated by a comma.
now i have this code harded coded in my controller and it loads fine.
my code that sets the scope variable.
soaFactory.getStudent(studentnumber,carslocation)
.success(function (response){
if(JSON.parse(response) == "Object reference not set to an instance of an object.")
{
//this code will hide any previous student info if a student is not returned
$scope.noStudentReturned = false;
$scope.students = null;
$scope.curStudentFirstName= null;
$scope.curStudentLastName = null;
$scope.curStudentSchool= null;
$scope.curStudentStatus= null;
$scope.curStudentProgram= null;
}
else
{
var parsedResponse= JSON.parse(response);
//alert("parsedResponse :" + parsedResponse );
//var parsedAgain= JSON.parse(parsedResponse);
// alert("parseAgain: " + parsedResponse);
// $scope.students = [parsedResponse];
$scope.students = [JSON.parse(parsedResponse)];
$scope.noStudentReturned = true;
if ($scope.students.length == 1)
{
//if only one student returned call this function.
$scope.setStudent(e,0);
}
else
{
}
}
})
.error(function (error){
alert(error);
$scope.noStudentReturned = false;
$scope.students = null;
$scope.curStudentFirstName= null;
$scope.curStudentLastName = null;
$scope.curStudentSchool= null;
$scope.curStudentStatus= null;
$scope.curStudentProgram= null;
});
Key Line
$scope.students = [JSON.parse(parsedResponse)];
debugger just says syntax error.
now this code works fine for one set of data. but not more than one.
Please help
Thanks
joe
I have a web service that returns a serialized JSON data string. An example of what is returned is:
{"Campus":"xxxx",...,"StudentLastName":"xxxx"}, {"Campus":"xxxx",...,"StudentLastName":"xxxx"}
This is not a string, these are two json object separated by a comma. Or maybe you forgot to paste the outer quotes.
If your service is likely to return multiple students, which seems the case by looking your code, ensure that you receive as a response objects wrapped in an array. Like that :
Students returned by the service :
[{
"Campus": "4444",
"Program": null,
"Selected": "false",
"Status": "NEW",
"Status2": null,
"Status3": null,
"StudentID": 00000,
"StudentFirstName": "somename",
"StudendMiddle Name": "",
"StudentLastName": "somename"
},
{
"Campus": "ssdd",
"Program": "smith",
"Selected": "false",
"Status": "xxxx",
"Status2": "xxxx",
"Status3": null,
"StudentID": 00000,
"StudentFirstName": "somename",
"StudendMiddleName": "I",
"StudentLastName": "somename"
}];
Then in your success handler you'll just have to read this array. Oh, by the way, if you want to check if students are returned or not, please do never ever write something similar :
if (JSON.parse(response) == "Object reference not set to an instance of an object.") {
// if a student is not returned
}
Now that the students are returned as an array, the test could be simply rewrited as :
if (response.length === 0) {
// no students
}
Your json data will not validate for 2 reasons:
You need to wrap them as an array of objects
Values in JSON string should be quoted.
The truth is you might get away with it in some cases but not if you're dealing with numbers.
So, "StudentID":00000 will never get parsed but "StudentID":"00000" will.
Bottom line: wrap your objects as an array, like nweg said, put quotes to all values and it will get parsed fine.
For example, this gets parsed fine:
var test = '{"Campus":"BMSB","Program":null,"Selected":"false","Status":"NEW","Status2":null ,"Status3":null,"StudentID":"00000","StudentFirstName":"Ioneu0027a","StudendMiddle Name":"","StudentLastName":"Byra"}, {"Campus":"BMFW","Program":"Accounting- Diploma","Selected":"false","Status":"GRAD","Status2":"GRAD","Status3":null,"StudentID":"00000","StudentFirstName":"Kathryn","StudendMiddleName":"I","StudentLastName":"Eib"}';
var testparse = JSON.parse( '[' + test + ']' );
And the only thing i changed in your json string was the quotes in a couple of number values.
The JSON you are returning is invalid. When returning multiple objects like you are you need to return them in an array, not objects separated with a comma. It works with one set of data because you are only sending one object which is valid JSON.
So, to fix this you need to either send the objects back already in an array which is the preferable method. Or you need to parse your response in a way that you can parse each object into it's own string before running json.parse on it and then add it to the array. Bottom line is you are trying to parse invalid JSON.
Your JSON is invalid because it has multiple root elements when you have two objects not enclosed in an array. One object is one root element (valid), two objects are two root elements (invalid), two objects in an array equal one root element (valid). The array is the root element then. Run your JSON through something like http://jsonformatter.curiousconcept.com/ to see the issue first hand.
Essentially I'm trying to parse JSON and assigning the results to variables, one of which is "var = JSON.class;" with class being what's returned in the JSON. However, flash won't let me parse it because it's called class which it uses to create new classes. Is there any workaround or will I not be able to grab this node?
I'm not sure if this is what you're asking, but if you have a property in your JSON object named "class", you should be able to parse it like as shown below.
// assuming JSON object looks like this, and is stored in a var named 'jsonData'
var jsonData:Object = { "id": 0, "class": "MyClassName", "values": [1,2,3] }
// trying to parse like this won't work w/keywords like 'class':
var parsedValue : String = jsonData.class;
// parse it with this way, using the square brackets:
var parsedValue : String = jsonData["class"];