How to read Json data using ng-repeat - javascript

I am working with Express 3 version of the NodeJs and have a SQL query which fetched the data from the database and then I applied JSON.Stringify and then JSON.PARSE function on the results obtained from the SQL query.
My JSON data looks like something like this. result is something on which I am saving my results.
Output at Console of Node Eclipse:
Database Results: [object Object],[object Object],[object Object]
result [object Object],[object Object],[object Object]
On the Angular side I used the below methods:
$scope.myResult = response.jsonParse;
console.log($scope.myResult);
I am using the Firebug to see my results and I can see the data on Firebug console as in JSON format:
{
"jsonParse": [{
"ITEM_CODE": 3,
"ITEM_NAME": "SONY",
"ITEM_DESC": " 44 inches",
"ITEM_PRICE": 170,
"ITEM_QTY": 4,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "TV",
"Group_Name": "Electronics"
}, {
"ITEM_CODE": 4,
"ITEM_NAME": "GIBSON",
"ITEM_DESC": "ACOUSTIC ",
"ITEM_PRICE": 110,
"ITEM_QTY": 6,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "ENTERTAINMENT",
"Group_Name": "INSTRUMENTS"
}, {
"ITEM_CODE": 5,
"ITEM_NAME": "Marvel Avenger",
"ITEM_DESC": "Captain America ",
"ITEM_PRICE": 110,
"ITEM_QTY": 6,
"SELLER_FIRSTNAME": "sagar",
"SELLER_LASTNAME": "kaw",
"EMAIL": "sagar.kaw#gmail.com",
"SELLER_USERNAME": "sagkaw",
"category": "Kids Toy",
"Group_Name": "TOYS"
}]
}
I copied the JSON data to myResults:
}).success(function(response){
$scope.myResult = response.jsonParse;
Now I have to get this data print on my HTML where I am using
ng-repeat="result in myResult">
<p><Strong>Item Name : </Strong>{{result.ITEM_NAME}}</p>
<p><Strong>Item Description : </Strong>{{result.ITEM_DESC}}</p>
But its not printing anything.
But if I do
{{result}} : It prints whole data on the screen.
I have to print the data in differently for different Item code.

This happens because your myResult variable is binded to the whole data returned from your server. Instead of doing this
$scope.myResult = response.jsonParse;
do
$scope.myResult = response.data.jsonParse;

Related

Get json array value from observable and give data to frontend

Trying get JSON array from json-server using observables and then giving the value to frontend and perform search on the JSON array received through observable
created a service and used HTTP get to connect to server and subscribed to it
created for loop to get value from returned value of subscription
**service.ts**
export class FormdtService {
baseul='http://localhost:3000/objects'//jsonserver url
constructor(private http:HttpClient) { }
getdt():Observable<any>{
return this.http.get(this.baseul)
}
}
**component.ts**
export class FormsComponent implements OnInit {
constructor(public fbu:FormBuilder,private fdts:FormdtService) {}
//creates the reactive form
form=this.fbu.group({
un:'',
id:''
})
// baseul='http://localhost:3000/objects/';
//ngsubmit control of form brings this function
ser(){
this.fdts.getdt().subscribe(dt=>{
console.log("data: "+dt[0])
this.formdt.push(dt)
//console.log("formdt :"+this.formdt[0])
for (let ite in this.formdt){
let ite1=JSON.parse(ite)
// console.log("ite :"+this.formdt[ite]);
//console.log("ite1"+ite1);
this.idlist.push(ite1.person.bioguideid.value)
if(ite1.person.bioguideid.stringify==this.idsearch)
this.objson=ite1
}});
}
idsearch:string
formdt:string[]
idlist:string[]
objson:JSON
ngOnInit() {
}
//this function is attached to button in frontend
ser(){
this.fdts.getdt().subscribe(dt=>
this.formdt.push(dt)//subscribes to service
for (let ite in this.formdt){
let ite1=JSON.parse(ite)
this.idlist.push(ite1.person.bioguideid.value)
if(ite1.person.bioguideid.value==this.idsearch)
this.objson=ite1
})}
**json**
[
{
"caucus": null,
"congress_numbers": [
114,
115,
116
],
"current": true,
"description": "Senior Senator for Tennessee",
"district": null,
"enddate": "2021-01-03",
"extra": {
"address": "455 Dirksen Senate Office Building Washington DC 20510",
"contact_form": "http://www.alexander.senate.gov/public/index.cfm?p=Email",
"fax": "202-228-3398",
"office": "455 Dirksen Senate Office Building",
"rss_url": "http://www.alexander.senate.gov/public/?a=rss.feed"
},
"leadership_title": null,
"party": "Republican",
"person": {
"bioguideid": "A000360",
"birthday": "1940-07-03",
"cspanid": 5,
"firstname": "Lamar",
"gender": "male",
"gender_label": "Male",
"lastname": "Alexander",
"link": "https://www.govtrack.us/congress/members/lamar_alexander/300002",
"middlename": "",
"name": "Sen. Lamar Alexander [R-TN]",
"namemod": "",
"nickname": "",
"osid": "N00009888",
"pvsid": "15691",
"sortname": "Alexander, Lamar (Sen.) [R-TN]",
"twitterid": "SenAlexander",
"youtubeid": "lamaralexander"
},
"phone": "202-224-4944",
"role_type": "senator",
"role_type_label": "Senator",
"senator_class": "class2",
"senator_class_label": "Class 2",
"senator_rank": "senior",
"senator_rank_label": "Senior",
"startdate": "2015-01-06",
"state": "TN",
"title": "Sen.",
"title_long": "Senator",
"website": "https://www.alexander.senate.gov/public"
},//end of single json array object
{
"caucus": null,
"congress_numbers": [
114,
115,
116
],
"current": true,
"description": "Senior Senator for Maine",
"district": null,....same repetition of structure
The ser function should give whole JSON array present in server to formdt[] and then iterate over it and get every object and convert to JSON and push bioguide to id array,search id from input and match with JSON nested value of each object in the array
nothing happens gives error in console :
_this.formdt is undefined at line 37 (this.fdts.getdt().subscribe(dt=>this.formdt.push=dt))
Given error is pretty explicit : this.formdt is undefined.
You've declared preperty type but haven't initialize it.
So replace formdt:string[] with formdt:string[] = []

jQuery Pull array from JSON response into new variable

Thank you for the help in advance. I am using a plugin which is expecting a JSON response to be an array not a object. Below is a sample of the JSON response I am getting
{
"instruments": [
{
"id": 3316,
"code": "WES",
"market_code": "ASX",
"name": "Wesfarmers Limited",
"currency_code": "AUD",
"pe_ratio": 16.38,
"nta": 4.44,
"eps": 2.55,
"current_price": 41.78,
"current_price_updated_at": "2017-10-26T16:10:09.000+11:00",
"sector_classification_name": "Retail Trade",
"industry_classification_name": "Food Retail",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
{
"id": 2955,
"code": "RIO",
"market_code": "ASX",
"name": "Rio Tinto Limited",
"currency_code": "AUD",
"pe_ratio": 14.95,
"nta": 27.77,
"eps": 4.66,
"current_price": 69.66,
"current_price_updated_at": "2017-10-26T16:10:11.000+11:00",
"sector_classification_name": "Non-Energy Minerals",
"industry_classification_name": "Other Metals/Minerals",
"security_type": "Ordinary Shares",
"registry_name": "Computershare"
},
],
"links": {}
}
The array I need to pull out into its own JSON object is the instruments array.
Now typically I know I would access that data via (if the response variable was called data) data.instruments[0].name as a example which would give me Wesfarmers limited
but if I want that entire array to sit in a new variable, which can then be parsed, how can I get that to happen?
Cheers
arr=new Array(data.instruments)

Display json response in ajax jquery,

The JSON Response I'm getting,
{
"user_data": {
"id": 22,
"first_name": xxx,
"last_name": xxx,
"phone_number": "123456789",
},
"question_with_answers" : [
{
"id": 1,
"question_name": "Features of our project that you like (select one
or more):",
"answers": [
{
"id": 19,
"question_id": 1,
"customer_id": 22,
"option": "Location",
},
{
"id": 20,
"question_id": 1,
"customer_id": 22,
"option": "Architecture",
},
]
},
{
"id": 2,
"question_name": "Features of our project that you DID NOT like
(select one or more):",
"answers": [
{
"id": 22,
"question_id": 2,
"customer_id": 22,
"option": "Location",
},
]
},
{
"id": 3,
"question_name": "How soon are you looking to buy a new home?",
"answers": [
{
"id": 24,
"question_id": 3,
"customer_id": 22,
"option": "Immediately",
}
]
}
]
}
So that is how JSON response looks like, now I need to display data using jquery
My js code
function openModal(Id){
var CustomerId = Id;
$.ajax({
type : 'get',
url: 'customer-details',
data: {
'CustomerId':CustomerId
},
success: function(data)
{
//what I have to do here
}
})
}
The output I want is,
first_name : xxx
last_name : xxx
phone_number : 123456789
1.Features of our project that you like (select one or more):
ans: Location, Architecture
2.Features of our project that you DID NOT like (select one or more)
ans: Location
3.How soon are you looking to buy a new home?
ans: Immediately
Thats how my output should look like from above json response,Is it possible to get above output using that Json response I got
There are two variable that I have passed from backend like user_data and question_with_answers
In success handler first of all make your json into a array using
var obj = JSON.parse(data);
Now in data you have array of your response and you can use this like
obj.first_name
obj.last_name
Note:- may be you have issue in JSON.parse so use first
var data = json.stringify(data)
after that use Json.parse function and use above data variable
this data
You have to set the dataType in the $.ajax call, set it to dataType:"json"...
After that, you got on the data variable in the success the json object and you can access it like data.user_data or data.id or data.first_name.
If you dont define the json as dataType, it will not work properly.
Addition
If you want to display the content of "question_with_answer" you have to iterate trough it, like ....
for (i in data.question_with_answer) { alert(data.qestion_with_answer[i]); }

IBM Worklight - Parse JSON response

How I can parse JSON response inside my javascript code? After I invoke my worklight adapter, I got this result.
{"linkAccountList": [{
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "1001328000",
"accountHolderName": "LELY HERNAWATI"
}, {
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "30000000100677",
"accountHolderName": "LELY HERNAWATI"
}, {
"accountRule": "1",
"accountCurrencyISO": "IDR",
"nickName": "",
"accountCurrency": "016",
"accountTypeDisplay": "",
"accountType": "",
"accountNo": "2003500382",
"accountHolderName": "LELY HERNAWATI"
}]
}
Then I store the value inside sessionStorage.
sessionStorage.setItem("linkAccountList", result.invocationResult.linkAccountList);
After that I alert the value, it's not what I wanted even already JSON.stringify() it.
linkAccountList :: "[object Object],[object Object],[object Object]"
What I want is exactly like result above.
My success function
function welcomeSuccess(result){
WL.Logger.debug("List retrieve success");
busyIndicator.hide();
sessionStorage.setItem("linkAccountList", result.invocationResult.linkAccountList);
WL.Logger.debug("linkAccountList :: " + JSON.stringify(sessionStorage.linkAccountList));
}
SessionStorage will only store strings. When you put something into SessionStorage, you should stringify it and when getting it back, do a JSON.parse().
function welcomeSuccess(result){
WL.Logger.debug("List retrieve success");
busyIndicator.hide();
sessionStorage.setItem("linkAccountList", JSON.stringify(result.invocationResult.linkAccountList));
WL.Logger.debug("linkAccountList :: ", JSON.parse(sessionStorage.linkAccountList));
}
What happened in your case was that when it put the value in the SessionStorage, it invoked the toString() method of the array which returned "[object Object],[object Object],[object Object]" and that is what you got back.

Iterate over JSON array

I've read several examples of how to do what I want but none seem to work. I want to iterate over a JSON array but it's not working for me. When I look in chromes js console my data looks like this:
"[\r\n {\r\n \"EntryId\": 3,\r\n \"Title\": \"Tiny Living For sales\",\r\n \"Description\": \"This is a house for sale\",\r\n \"AddressViewModel\": {\r\n \"AddressId\": 3,\r\n \"Street1\": null,\r\n \"Street2\": null,\r\n \"City\": \"Los Angeles\",\r\n \"LocationId\": 5,\r\n \"LocationName\": \"California\",\r\n \"PostalCode\": null,\r\n \"Phone\": null,\r\n \"Latitude\": 34.052234,\r\n \"Longitude\": -118.243685\r\n },\r\n \"EntryCategoryName\": \"Houses for Sale\",\r\n \"EventStartDate\": null,\r\n \"EventEndDate\": null\r\n },\r\n {\r\n \"EntryId\": 2,\r\n \"Title\": \"Tiny Living Workshop\",\r\n \"Description\": \"This is a workshop\",\r\n ...
And if I turn it into an object by doing so:
var myObject = eval('(' + locations + ')');
It looks like this (formated):
[
{
"EntryId": 3,
"Title": "Tiny Living For sales",
"Description": "This is a house for sale",
"AddressViewModel": {
"AddressId": 3,
"Street1": null,
"Street2": null,
"City": "Los Angeles",
"LocationId": 5,
"LocationName": "California",
"PostalCode": null,
"Phone": null,
"Latitude": 34.052234,
"Longitude": -118.243685
},
"EntryCategoryName": "Houses for Sale",
"EventStartDate": null,
"EventEndDate": null
},
{
"EntryId": 2,
"Title": "Tiny Living Workshop",
...
But when I try to iterate over it (either the raw JSON or the object) it gives me each letter of the JSON, not each object in the array
for (var i = 0; i < myObject.length; i++) { console.log(myObject[i]); }
Like so:
"
[
\
r
\
Thanks
You evaluate the JSON and assign the result to "myObject", and then you attempt to iterate through "locations". It's no wonder that that doesn't work :-)
I figured it out. I was returning the JSON from my controller like this
return Json( jsonResults, "text/html");
I had to do this on a different controller to prevent IE from prompting the user to save the JSON results.
Anyways, that was putting quotes around the data so it wasn't being parsed correctly.
So I am now returning:
return Json( jsonResults);
Hopefully I don't have the IE problem (tested in 9 and didn't see it)

Categories

Resources