This question already has answers here:
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I have this JSON array with a lot of person data every one with a type like "hr" or "accounting".
the JSON array looks like this:
{
"0": {
"id": "2",
"name": "blabla",
"type": "hr"
},
"1": {
"id": "3",
"name": "bub",
"type": "hr"
},
"2": {
"id": "4",
"name": "ula",
"type": "accounting"
},
"3": {
...
}
}
I want to display them in an ul like this:
<ul>
<li><p>hr</p>name: blabla<p></li>
<li><p>hr</p>name: bub<p></li>
<li><p>hr</p>......</li>
</ul>
<ul>
<li><p>accounting</p>name: ula<p></li>
<li><p>accounting</p>......</li>
</ul>
but i have no clue how to separate the JSON array or how to properly loop through it to display it like that.
Try this:
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div class="container"></div>
<script>
var json={
"0": {
"id": "2",
"name": "blabla",
"type": "hr"
},
"1": {
"id": "3",
"name": "bub",
"type": "hr"
},
"2": {
"id": "4",
"name": "ula",
"type": "accounting"
}
};
var previous_type=json[0].type;
var _html="<ul>";
$.each(json, function(index,key) {
if (previous_type!=key.type) {
_html+="</ul><ul>";
}
previous_type=key.type;
_html+="<li><p>"+key.type+"</p><p>name: "+key.name+"</p></li>";
});
_html+="</ul>";
$('.container').html(_html);
</script>
</body>
</html>
It creates a new ul for every different type.
Output of container:
<div class="container">
<ul>
<li>
<p>hr</p>
<p>name: blabla</p>
</li>
<li>
<p>hr</p>
<p>name: bub</p>
</li>
</ul>
<ul>
<li>
<p>accounting</p>
<p>name: ula</p>
</li>
</ul>
</div>
this will basically do what you want for one department. You can use it for each department by putting an if in the each loop and checking it against value.type
var new_html = "<ul>";
$.each('name_of_json_array', function(key, value){
new_html+="<li><p>"+value.type+"</p><p>name: "+value.name+"</p></li>";
});
new_html+="</ul>";
$('#some_container_element').append(new_html);
Related
I'm trying to show all categories from my JSON file in a menu. Can anyone help me with the JavaScript code for this? I have tried a couple of things but all in vain.
HTML: (static)
<ul class="cd-faq-categories" id="onderwerp">
<li><a class="selected" href="#algemeen">Test</a></li>
<li>Test2</li>
<li>Test3</li>
<li>Test4</li>
<li>Test5</li>
</ul> <!-- cd-faq-categories -->
JSON structure:
{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
}
Can anyone help me with this? I'm trying to have the name and href the same in the HTML tag, so for example:
<li>$c{category}</li>
Here is working solution:
var data =[
{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},
{
"id": 3,
"category": "Eten 2",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},
{
"id": 3,
"category": "Eten 3",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
}
]
const liTemplate = (category) => `${category}`
data.forEach(item => {
var child = document.createElement('li');
child.innerHTML = liTemplate(item.category);
document.querySelectorAll('.cd-faq-categories')[0].appendChild(child);
})
The solution is taking Json object. Iterate through all items and append to DOM li elements with simple vanilla JS appendChild method.
JSON file is a just a text file, so in order javascript to understand it like an obj. you must parse it. You must use JSON.parse() function.
var data = JSON.parse('{
"id": 3,
"category": "Eten",
"question": "Vis",
"answer": "Ham",
"date": "29-11-18"
},');
<li>$c{data.category}</li>
In my Angular1.x app, my models maps to my radio selection correctly, however the radio button itself is not selected except for the very last one. Not really sure what the problem is. I created a very small example below to illustrate this behaviour. Any help is greatly appreciated.
http://plnkr.co/edit/dgGCvtOEb9WKTNtQHjqd?p=preview
angular.module('todoApp', [])
.controller('TodoListController', function() {
var todoList = this;
todoList.questions = [{
"category": "Movies",
"questions": [{
"title": "M1",
"score": "4",
},
{
"title": "M2",
"score": "2",
}
]
},
{
"category": "Foods",
"questions": [{
"title": "F1",
"score": "3",
},
{
"title": "F2",
"score": "4",
}
]
},
{
"category": "Sports",
"questions": [{
"title": "S1",
"score": "5",
}]
}
];
});
<!doctype html>
<html ng-app="todoApp">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.1/angular.min.js"></script>
<script src="todo.js"></script>
<link rel="stylesheet" href="todo.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/twitter-bootstrap/2.0.4/css/bootstrap-combined.min.css">
</head>
<body>
<h2>Todo</h2>
<div ng-controller="TodoListController as todoList">
<div ng-repeat="(ccKey, cc) in todoList.questions">
<hr/>
<div>
<b style="color: red;">Category</b> : {{cc.category}}
</div>
<div ng-repeat="(qqKey, qq) in cc.questions">
<br/>
{{qq.title}} : Selected Score: {{qq.score}}
<br/>
<div ng-repeat="n in [].constructor(5) track by $index">
<input type="radio" ng-model="qq.score" name="q-{{ccKey}}-{{qqKey}}" value="{{$index+1}}"><br/>Score: {{$index+1}} : Group: q-{{ccKey}}-{{qqKey}}
</div>
</div>
</div>
</div>
</body>
</html>
Try removing the name attribute from your <input type="radio"> tag. This seems to be causing a conflict with what Angular is doing to manage your radio tags. I am able to see all categories selected, and the selections are still grouped within a given question.
In the Angular input[radio] docs, they do not show using a name attribute: https://docs.angularjs.org/api/ng/input/input%5Bradio%5D
If what you want is the initial selection of the values when the page first loads,then use
ng-value="($index+1).toString()"
Since your scores are given as strings, you need to convert the number to string to match the score when you use "ng-value". Or better, you can just set your scores as integers and leave the rest of the code unchanged:
todoList.questions = [{
"category": "Movies",
"questions": [{
"title": "M1",
"score": 4,
},
{
"title": "M2",
"score": 2,
}
]
}, ....
Here is a modified plunker
This question already has answers here:
How can I group data with an Angular filter?
(8 answers)
Closed 7 years ago.
I am trying to show a list using ng-repeat but I couldn't figure out how to group it. This is my json:
{
"id": "1",
"name": "Andre Nascimento",
"client": "Lojas Mais"
},
{
"id": "1",
"name": "Andre Nascimento",
"client": "Fe comercio"
},
{
"id": "1",
"name": "Andre Nascimento",
"client": "Transtour"
},
{
"id": "2",
"name": "Carla Prata",
"client": "Fe comercio"
},
{
"id": "2",
"name": "Carla Prata",
"client": "Transtour"
}
I would like to getthe follow result
Andre Nascimento
*Lojas Mais
*Fe comercio
*Transtour
Carla Prata
*Fe comercio
*Transtour
you can use angular.filter module as explained in this answer. Then you would have something like
<ul ng-repeat="(key, value) in yourArray| groupBy: 'client'">
Group name: {{ key }}
<li ng-repeat="element in value">
player: {{ element.name }}
</li>
</ul>
this should do it.
here there is a fiddle
I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview
I need to create a dynamic nested ul\li list from json array.
NOTE! I can do that transformation my self using jQuery, but in this case i need to work with a string, since it's node.js and i don't have access to DOM.
Also the array can have different depth.
This is json data i work with and how it should look after transformation.
var data = [{"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
{"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
{"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
{"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}];
<ul>
<li>name_1</li> //depth 0
<li>name_2 //depth 0
<ul>
<li>name_3 //depth 1
<ul>
<li>name_3</li> //depth 2
</ul>
</li>
</ul>
</li>
</ul>
I hope this is clear. If not please ask any questions in the comment.
Thank you in advanced.
Try this:
var data = [{"id": "1", "name": "name_1", "parent_id": "0", "depth": "0"},
{"id": "2", "name": "name_2", "parent_id": "0", "depth": "0"},
{"id": "3", "name": "name_3", "parent_id": "1", "depth": "1"},
{"id": "4", "name": "name_4", "parent_id": "3", "depth": "2"}];
var initLevel = 0;
var endMenu =getMenu("0");
function getMenu( parentID ){
return data.filter(function(node){ return ( node.parent_id === parentID ) ; }).map(function(node){
var exists = data.some(function(childNode){ return childNode.parent_id === node.id; });
var subMenu = (exists) ? '<ul>'+ getMenu(node.id).join('') + '</ul>' : "";
return '<li>'+node.name + subMenu + '</li>' ;
});
}
console.log( '<ul>'+endMenu.join('')+ '</ul>');
However, I think the correct output based on your data will be something like:
<ul>
<li>name_1
<ul>
<li>name_3
<ul>
<li>name_4</li>
</ul>
</li>
</ul>
</li>
<li>name_2</li>
</ul>
Here is the JSFiddle sample
Updated Version:
http://jsfiddle.net/LqES7/47/
I'd first convert the flat data to hierarchical json, using something like this, so it's more iterable. Then recursively iterate the JSON and add every element to a string.
If i understand the question correctly you are trying to genereat a list in html from a array of objects.
So if your not using JQuery, probably one of these will help you out:
Create ul and li elements in javascript.
Create a UL and fill it based on a passed array
And if your using JQuery, probably this will help you out:
How to generate UL Li list from string array using jquery?