Fetching nested JSON data using key,value - json

Below is my method from .ts file. With this method the keys are displayed but I am unable to fetch the nested JSON data.
generateArr(obj) {
return Object.keys(obj).map((key) => {
console.log(key, obj[key]);
return {key: key, value: obj[key]};
});
}
Below is my HTML code.
<li *ngFor="let ob of books">
<p *ngFor="let objArrEle of generateArr(ob);let i=index">
{{objArrEle.key}}: {{objArrEle.value}}
</p>
</li>
Please tell me the solution.

If you are trying to fetch the nested JSON using interpolation {{}} in HTML, it will display[Object object]. If you want to display the nested data also, you may want to recursively call generateArr(obj) for each nested property. If you are using Angular 7, have a look at KeyValuePipe.
Created a solution for you using stackblitz https://stackblitz.com/edit/angular-nestedjson. you can nest JSON for any level. I'm not so good with CSS, please fell free to change that.

Related

Accessing JSON data in template in Django

I have a view that retrieves a JSON file like this:
json_lang = requests.get('path/to/file.json').json()
return render(request, "chat/chatroom.html", {'jsonLang': json.dumps(json_lang)})
Let's say the json file is structured somewhat like this:
{
"en": {
"action.send": "Send",
"chat.joined": "joined the chatroom",
"chat.left": "left the chatroom",
...
}
If I try to access one of those strings in a template like this {{ jsonLang.en.chat.joined }} I get an empty output.
Other methods, like trying to access it like this jsonLang["en"]["chat.joined"] result in an error:
TemplateSyntaxError at /chat/
Could not parse the remainder: '["en"]["chat.joined"]' from 'json_lang.["en"]["chat.joined"]'
What's the correct method to do this?
Firstly, 'jsonLang': json.dumps(json_lang) means that you pass a string to template. You should use 'jsonLang': json_lang to pass it as a Python dictionary.
Secondly, as dictionary lookup in Django templates are implemented with dot notation, this breaks if the key itself contains a dot.
One solution is adding a quick template filter that allows to access dictionary items by keys with dots - Access a dictionary element in the Django template with a variable

How to iterate json key and value over html in aurelia js

I have json as below :
this.myObj = {
keyOne: 'myValue1',
keyTwo: 'myValue2',
keyThree: 'myValue3',
keyFour: 'myValue4',
};
I want to set key and value in my html.I have tried as below code :
<ul>
<li repeat.for="prop of myObj | objectKeys">${prop}</li>
</ul>
But my code is not work. Please give me solution regarding this.
I am a bit confused about what you wish to accomplish here.
I assume you wish to get the keys of myObj and loop through them.
I suggest reading about repeaters at aurelia documents.
For a solution that may get you going, add this to your modal file:
export class ObjectKeysValueConverter {
toView(value) {
return Object.keys(value);
}
}
Object.keys( myObj ) will return an array, which repeat.for attribute requires. It can't iterate objects by default.

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]

How to bind json object with variable in typescript Angular2?

I have one json file and i want to bind with some variable to show on UI.
testjson= {"date":1468497879354,"faulty":"F-3","mileage":"150,900 mls","search":[]}
and in html
<div>
<span>{{ testjson }}</span><--- here i am getting above json object
Date:{{date}}
Faulty:{{faulty}}
Mileage: {{mileage}}
<div>
How do i bind so that i can get perticular object value ??
You can do it like this:
<div>
<span>lala</span>
Date:{{testjson.date}}
Faulty:{{testjson.faulty}}
Mileage: {{testjson.mileage}}
<div>
Plunker Example
The values may be obtained directly using string interpolation.
{{testjson.date}}
{{testjson.faulty}}
etc...
that's it :)

How do we use a JSON result from $http.get in Angular?

I'm getting a json using $http.$get, but to it be "compatible" with Angular, I'm having to convert it this way:
$http.get('/api/v1.0/plans').
success(function(data) {
var plans = [];
for(var propertyName in data)
{
if (data.hasOwnProperty(propertyName))
{
plans.push(data[propertyName]);
}
}
$scope.plans = angular.fromJson(data);
});
But, of course, I think this would be the way to go in this case, as shown in docs:
$http.get('/api/v1.0/plans').
success(function(data) {
$scope.plans = data;
});
I can see the difference between the objects, I just don't know how to fix it:
data (not accepted by angular)
Object {alfa: Object, beta: Object, delta: Object, omega: Object}
plans (converted and accepted by angular)
[Object, Object, Object, Object]
Could you, please, tell what I'm doing wrong?
You need to elaborate a bit more about what kind of "compatible" problem you refered to in your first sentence. As far as I know, both JSON representations work just fine in Angular for me.
I believe the question here boils down to how the data will be used after being set to $scope.plans. If you are trying to use ng-repeat with $scope.plans afterward, then how you iterate will differ slightly depending whether the data you receive is a JSON object or JSON array.
For JSON object, you use
<tr ng-repeat="(name, plan) in plans">
<td> {{name}} </td> <td> {{ plan | json }} </td>
</tr>
For JSON array, you use
<tr ng-repeat="plan in plans">
<td> {{$index}} </td> <td> {{ plan | json }} </td>
</tr>
Of course, for plan specified in HTML snippets above, you can access object inner fields with dot notation as usual (i.e., {{plan.title}}, {{plan.description}}, etc.). {{plan | json}} just converts JSON object into string so you can see object content directly in HTML.
For details on how to use ngRepeat, you can read more at https://docs.angularjs.org/api/ng/directive/ngRepeat
In case a (Object {alfa: Object, beta: Object, delta: Object, omega: Object} your api return object so you have to define plans as a object not array that should works
$scope.plans = {}; // <-object
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
in case you api will return array of object you have to define plans as a array ie:
$scope.plans = []; // <-array
$http.get('/api/v1.0/plans').
success(function(data) {
angular.copy(data, $scope.plans);
});
Please see bin here