Reputation: 4097
I need to read the following JSON text from my fetched database, below was my sample code:
{{questionData1[0].qst_cnt_options[0].left}}
The real data in qst_cnt_options
was:
[{left:'Benda Hidup',right:'Benda Mati'}] //Fetched from database and as text
When I tried to read back, the output was only
[
. How to solve this problem?
Upvotes: 0
Views: 66
Reputation: 18647
Since the fetched value from the database is simple text, use JSON.parse
to parse into a json object and retrieve it.
[{left:'Benda Hidup',right:'Benda Mati'}]
this is a string, so returning [
as first value.
Method1: just return the JSON parsed value from the contrller,
In your controller:
app.controller('myCtrl',function($scope){
$scope.qst_cnt_options = $scope.questionData1[0].JSON.parse(qst_cnt_options)
});
In your view:
{{qst_cnt_options[0].left}}
Method2:
app.controller('myCtrl',function($scope){
$scope.qst_cnt_options = questionData1[0].JSON.parse(qst_cnt_options)
$scope.parJson = function (json) {
return JSON.parse(json)[0];
}
});
View:
{{qst_cnt_options.parJson(qst_cnt_options.qst_cnt_options)}}
Upvotes: 1
Reputation: 3384
Update: Encapsulate the strings (including left, right) with double quotes. That should sort it out.
It might appear that what you are fetching back isn't resolving as proper JSON because of surrounding [] which might be forcing the parser to treat it as an Array.
Try removing the [] and see if that works
I ran further checks on the input and as per the JSON validators you should be encapsulating your strings in double quotes. There are no quotes around left and right qualifiers. That might be your problem.
Try the online validator here https://jsonformatter.curiousconcept.com/
Upvotes: 0