Trouble Parsing JSON object in Angular - html

I am having trouble in parsing the JSON object, not sure where I am wrong?
Here is HTML:
<div ng-controller="MyCtrl">
<div ng-repeat="user in _users" ng-init="myInfo=parJson(user.response)">{{myInfo.docs[0].FIRST_NAME}}</div>
</div>
Here is Angular:
var myApp = angular.module('myApp', []);
function MyCtrl($scope) {
$scope.getName = function(user) {
return "Names";
};
$scope._users = [{
"responseHeader": {
"status":0,
"QTime":1,
},"response":{
"docs":[{
"FIRST_NAME":"John",
"LAST_NAME" : "Smith"}]
}
}];
$scope.parJson = function(json) {
return JSON.parse(json);
}
}
myApp.controller("MyCtrl",MyCtrl);

From the code i can see that "user.response" is already a JSON object, you don't need to parse it again. One thing you can do if you are not sure if your response is a JSON object or JSON string you can add a check in you "parJson" function
$scope.parJson = function(json) {
if(typeof json != "object")
return JSON.parse(json);
else
return json;
}

You have extra comma after QTime property. Remove it and try again. Use JSON Lint to validate your json.

Related

How to extract value from json response in postman, whose key has '.' in it

It is pretty straight forward to to get a value of a key from json response in postman say :
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData.value);
});
For JSON Response
{
"value": "task-1405"
}
I am not able to extract json value in the below case where key has a '.' as part of its string.Can any one help me with this.
"result": {
"cluster.moid": "domain-c433242"
}
I tried the following below code:
pm.test("abc", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var moid = result.'cluster.moid' ;
pm.environment.set("clusterMoid", moid);
});
Could figure out to extract value for the above case, The below code works
pm.test("StatusForAddClusterApplyCheck", function () {
var jsonData = pm.response.json();
var result = jsonData.result;
var jsonString = JSON.stringify(result).substring(17,31);
pm.environment.set("clusterMoid", jsonString);
});
But only if the string length are constants.
Any other answer in case string length are dynamic?
In javascript (And also in postman), object properties can be accessed with '.' operator or with associative array indexing using []. The same goes for JSON objects.
ie. object.key is equivalent to object["key"].
this should do the trick for you:
pm.test("AddCluster", function () {
var jsonData = pm.response.json();
pm.globals.set("taskIdCluster", jsonData["cluster.moid"]);
});

Calling the JSON correctly

I have a JSON array fetched from the service to the controller. I'm able to display the JSON array in the console. But when a specific item from the JSON, is called it display's undefined. So how do I call it correctly so that I can use it in my view.
Controller:
$scope.onViewLoaded = function() {
callingService.getdata($scope.datafetched);
}
$scope.datafetched = function(response) {
debugger;
if (response) {
$rootScope.mainData = response;
$scope.localizeddataTypes = getLocalizedCollection($scope.mainData);
}
}
$scope.editFunction = function(key) {
console.log($scope.mainData);
debugger;
console.log($scope.mainData.keyValue);
}
Here console.log($scope.mainData); display's the JSON array but console.log($scope.mainData.keyValue); is displayed as undefined. And my JSON looks like
{
keyValue: "1234DEF56",
animals: {
name:"dog",
color:"brown"
},
birds:{
name:"canary",
color:"yellow"
}
}
So, how do I overcome this problem and why do I get it as Undefined.
Just a curiosity stuff. I feel that the content in that variable is stored in string format and not JSON or JavaScript Object. Try this, and see if that works?
$scope.mainData = JSON.parse($scope.mainData);
console.log($scope.mainData.keyValue);

angular2 transformRequest usage for xml to json conversion

I managed to convert xml response into json format in angular 1 using the code below. But how can I use similar code in angular2,
var xml = function () {
$http.get("./app/sampleXML.xml",
{
transformResponse: function (cnv) {
var x2js = new X2JS();
var aftCnv = x2js.xml_str2json(cnv);
return aftCnv;
}
})
.success(function (response) {
console.log(response);
});
}
Angular2:
getXml() {
this.http.get('../../jsonConfig/sampleXML.xml')
.map(response => response.text())
.subscribe(data => {
if(data) {
console.log(data);
}
});
}
This is what worked for me :
xml_str2json(extractXML(data.text(),'string1','string2'))
where xml2json comes from the following library :
https://github.com/abdmob/x2js
and extractXML is a string function that enables me to extract the xml body from the SOAP response.
I could not find any document on the methods that could be applied on a Response.
Hope this may help.
Cheers.

How to add JSON object into JSON array using angular JS?

I have problem while parsing single json object.
Assume that the below data get from server
{
"root": {
"data": [
{
"name": "Raj",
"age": "22"
},
{
"name": "Janu",
"age": "22"
}
]
}
}
And my script is
Script.js
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
$scope.myDatas = response.root;
});
});
HTML
<div ng-repeat="i in myDatas.data">
Name: {{i.name}}
Age: {{i.age}}
</div>
I have no problem while the response data is more than 1. But If the response data is 1 then the json will be:
{
"root": {
"data": {
"name": "Raj",
"age": "22"
}
}
}
How to generically parse these json data ?
PLNKR: http://plnkr.co/edit/W4YK6BDtIBfVhnPpHVm1?p=preview
You need just slight change, check type of responsedata.root.data. If it is not array, convert it to array. Here is your code becomes.
Here is plnkr
// Code goes here
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !(response.root.data instanceof Array )){
response.root.data=[response.root.data]
}
$scope.myDatas = response.root;
});
});
You can normalize incoming data to always be an array. It's convenient to use Array.prototype.concat method for this:
$http.get("singledata.json")
.success(function(response) {
$scope.myDatas = response.root;
$scope.myDatas.data = [].concat($scope.myDatas.data);
});
Demo: http://plnkr.co/edit/UUWtDBK8qID1XoYeMXhu?p=preview
I would check if data is an array or not, and if not, just ammend the data to be an array:
Like this:
$http.get("singledata.json")
.success(function(response) {
if(response.root.data && !angular.isArray(response.root.data)){
var object = response.root.data;
response.root.data = [];
response.root.data.push(object);
}
$scope.myDatas = response.root;
});
You can check the whether the data is array or not. If not then you create the array as. Check this code its working.
For controller:
var myApp=angular.module('myApp',[]);
myApp.controller('myCtrl', function($scope, $http){
$http.get("manydata.json")
.success(function(response) {
var data = response.root.data;
if(data.constructor === Array){
$scope.myDatas = data;
}else{
$scope.myDatas = new Array(data);
}
});
});
For html:
<div ng-repeat="i in myDatas">
Name: {{i.name}}
Age: {{i.age}}
</div>
Hope this helps.

JSON output formatting

I am trying to format the JSON output through node js as shown below
[{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["100","test_bsc_interface","test_bsc_interface","test","Open Loop","regex","HPSA",null,null,"Asynchronous",null,"0"]},["101","check_tt","check_tt","test","Open Loop","None","Trouble Ticket","check_tt",null,"Synchronous",null,"0"]}
But currently i am getting the output as shown below
[{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["100","test_bsc_interface","test_bsc_interface","test","Open Loop","regex","HPSA",null,null,"Asynchronous",null,"0"]},{"headers":["id","name","description","type","actionmode","outputparser","dispatchtype","troubleticketaction","alarmaction","actionexecutionmode","cost","isparent__"],"values":["101","check_tt","check_tt","test","Open Loop","None","Trouble Ticket","check_tt",null,"Synchronous",null,"0"]}
Please find code snippet that i have used : may know whats the changes required in the code ::
var json_string=JSON.stringify(rows,null,2);
var json_object=setValue(JSON.parse(json_string));
if (!err){
console.log('The object are returning ',json_object);
var result = _.map(json_object, function(o) {
return {headers: _.keys(o), values : _.values(o)}
});
Your problem seems to be from another post I answered:
How to format the JSON object key/value pair
var json_string=JSON.stringify(rows,null,2);
var json_object=setValue(JSON.parse(json_string));
var result;
if (!err){
console.log('The object are returning ',json_object);
if (_.isArray(json_object) && json_object.length > 0) {
result = {
headers: _.keys(json_object[0]),
values: _.map(json_object, function(o) {
return _.values(o);
})
};
}
}