How to show JSON as formatted view in html - javascript

I need to view JSON in my html page as formatted view. JSON come from database. I need to show it nut in Formatted view.
Just like
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
}
Anyone have any idea or suggestion ? or any resource that may help.
Edited: I want to create a JSON parser. User input different json and can view in formatted view.

Try JSON.stringify(data), its a Javascript function. Hope it might help.
Refer: Detail Explaination
If you are using PHP then use json_encode
Refer: json_encode manual

Since your are using angular-js, you can simply load your JSON feed from your controller then use the ng-repeat function to iterate over the items into your view page. Here down a sample where of how your HTML view can look like and you may need to style and build the blocks as per your needs:
<span>items:</span>
<span>[</span>
<br/>
<div class="item" ng-repeat="item in items">
<span>{</span><br/>
<span class="field">year : {{item.year}}</span><br/>
<span class="field">boat : {{item.boat}}</span><br/>
<span class="field">position : {{item.position}}</span><br/>
<span>}</span>
</div>
You can find a working sample in this JSFiddle.

First: your remote JSON is invalid: it's missing an ending bracket for crews.
It should be like this:
{
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}] // Missing this bracket
}
You didn't mention if your JSON is remote or not. I'm assuming not, so I'll use a local JavaScript var with eval function in this sample code.
<script type="text/javascript">
var content = {
"crews": [{
"items": [
{
"year" : "2013",
"boat" : "Blue",
"position" : "1",
"name" : "Patrick Close",
"college" : "Pembroke",
"weight" : "14st 2lbs"
}, {
"year" : "2013",
"boat" : "Blue",
"position" : "2",
"name" : "Geordie Macleod",
"college" : "Christ Church",
"weight" : "13st 10lbs"
}]
}]
};
var json = eval(content);
for (c in json.crews) {
var crew = json.crews[c];
for (i in crew.items) {
var item = crew.items[i];
console.log(item.year);
console.log(item.boat);
console.log(item.position);
console.log(item.name);
}
}
</script>
I'm using console.log to output, so you'll be able to see data only if you open the browser console:

Related

array in array filter - javascript

hello i need help with array , as you can see my data
{
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
I can access elements such as id , title or logo because they are not arrays.
How can I loop through the data inside the array since there is an array in the category in yield?
var data = this.database.filter((item) => item.type == searchType)
var data = this.database.filter((item) => item.category == searchCategory)
It's okay because my type value doesn't have an array.
But when I enter my category value, it only gets the first index[0]. It does not look at other indexes.
in summary,
item.category[0] , item.category[1] , item.category[2]...........
How can I get index browsing like
if your data looks like this :
let data ={
"age" : "18",
"altKategoriler" : [ "Dramalar" ],
"category" : [ "Aksiyon", "Heyecanlı", "Gerilim" ],
"id" : 5240718100,
"img" : "https://i.ibb.co/k8wx5C8/AAAABW9-ZJQOg-MRljz-Zwe30-JZw-Hf4vq-ERHq6-HMva5-ODHln-Ci-OEV6ir-Rcjt88tcnm-QGQCKpr-K9h-Oll-Ln-Sbb-EI.jpg",
"izlenilmeSayisi" : 0,
"logo" : "https://i.ibb.co/Rb2SrcB/AAAABfcrhh-Rni-Ok-Ct2l-Rys-ZYk-Oi-T0-XTeagkrw-Mkm-U0h-Lr-WIQZHEHg-VXihf-OWCwz-Vv-Qd7u-Ffn-DFZEX2-Ob.webp",
"oyuncuKadrosu" : [ "Diego Luna", "Michael Pena", "Scoot McNairy", "Tenoch Huerta", "Joaquin Cosio" ],
"senarist" : [ "Doug Miro" ],
"time" : "3 Sezon",
"title" : "Narcos: Mexico",
"type" : "Dizi",
"videoDescription" : "Guadalajara Karteli'nin yükselişinin gerçek öyküsünü anlatan bu yeni ve cesur Narcos hikâyesinde, Meksika'daki uyuşturucu savaşının 1980'lerdeki doğuşuna tanıklık edin.",
"videoQuality" : "HD",
"videosrc" : "https://tr.vid.web.acsta.net/uk/medias/nmedia/90/18/10/18/19/19550785_hd_013.mp4",
"year" : "2021",
"yonetmen" : [ "Carlo Bernard", "Chris Brancato" ]
}
and if we have array of data you can do something like this :
myArray.filter(item=>item.category.indexOf(searchCategory)>=0)
but if you want to explore in object rather than array you can do this :
data.category.indexOf(searchCategory)>=0
You could make this a bit generic, by testing whether the targeted field is an array, using Array.isArray, and then call a filter on each element, and see if any is positive (using .some()). The filter can be function that is provided, so that it can perform a simple match, or apply a regular expression, or anything else.
Instead of testing with Array.isArray you could skip that step and check whether the value has a .some() method. If so, calling it will give the desired outcome, and otherwise (using the .? and ?? operators), the filter should be applied to the value as a whole:
Here is how that looks:
function applyFilter(data, field, filter) {
return data.filter(item => item[field]?.some(filter) ?? filter(item));
}
// Example use:
var data = [{
"category" : [ "Action", "Thriller", "Horror"],
"type" : "Series",
}, {
"category" : [ "Historical", "Romance" ],
"type" : "Theatre",
}];
// Find entries that have a category that looks like "roman*":
var result = applyFilter(data, "category", value => /^roman.*/i.test(value));
console.log(result);
If you are running on an older version of JavaScript, and don't have support for .? or ??, then use:
return data.filter(item => Array.isArray(item[field])
? item[field].some(filter)
: filter(item));

How to back and forth in array of data?

I have a following data which I am iterating on paragraph, which performs different task in different steps. I am not getting how to load selected view and controller in angular and make current as active.
http://prntscr.com/fisflz
[{
"0" : {
"name" : "Select Event"
},
"1" : {
"name" : "Connect"
},
"2" : {
"name" : "Configure"
},
"3" : {
"name" : "Test"
},
"4" : {
"name" : "Finish"
}
}]
Hint will appreciable.
Thanks

Javascript - Find (not remove) elements with duplicate properties in an object array

I want to fetch an object array, check if multiple properties are duplicate at the same time. Finally, the duplicate elements are meant to be alerted. i.e. for the array:
[
{
"language" : "english",
"type" : "a",
"value" : "value1"
},
{
"language" : "english",
"type" : "a",
"value" : "value2"
},
{
"language" : "english",
"type" : "b",
"value" : "value3"
},
{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
}
];
The alert should be: "Too many elements with language english and type a".
I sought for it, yet the answers were either dirty map/reduce implementations that made VisualStudio2015 pissed off or finding a full duplicates (not only based on specific properties)
Performance wise, I think the best option is to iterate on each element of the list while updating a counter of the encountered keys.
You want to alert when counter == 2. You should not test counter > 1 because it would repeat the same alert several times, when you have more than 2 pairs with the same language and same type.
var list = [{
"language" : "english",
"type" : "a",
"value" : "value1"
},{
"language" : "english",
"type" : "a",
"value" : "value2"
},{
"language" : "english",
"type" : "a",
"value" : "value3"
},{
"language" : "english",
"type" : "b",
"value" : "value3"
},{
"language" : "spanish",
"type" : "a",
"value" : "valor1"
},{
"language" : "spanish",
"type" : "a",
"value" : "valor2"
}];
var counter = {};
list.forEach(function(o) {
var key = o.language + '|' + o.type;
if((counter[key] = (counter[key] || 0) + 1) == 2) {
console.log('Too many elements with language '+o.language+' and type '+o.type);
}
});

java.lang.ClassCastException calling RedQueryBuilderFactory.create with args

This line in my JS file:
RedQueryBuilderFactory.create(config,
'SELECT "x0"."title", "x0"."priority" FROM "ticket" "x0" WHERE ("x0"."status" = (?))',
[]
);
works fine witih an empty array as the 3rd parameter. This parameter is supposed to be an array of strings according to the documentation and any sample code I can find. When I pass a string in the array it fails:
RedQueryBuilderFactory.create(config,
'SELECT "x0"."title", "x0"."priority" FROM "ticket" "x0" WHERE ("x0"."status" = (?))',
['in_process']
);
I get java.lang.ClassCastException in the Safari console. Here's the related part of the config if it's relevant:
var config = {
meta : {
tables : [ {
"name" : "ticket",
"label" : "Ticket",
"columns" : [ {
"name" : "title",
"label" : "Title",
"type" : "STRING",
"size" : 255
}, {
"name" : "priority",
"label" : "Priority",
"type" : "REF"
} ],
fks : []
} ],
types : [ {
"name" : "REF",
"editor" : "SELECT",
"operators" : [ {
"name" : "IN",
"label" : "any of",
"cardinality" : "MULTI"
}]
} ]
}
};
Looks like this is a bug in passing in parameter values. Internally it is expecting a collection but this is not happening.
Best if you raise a https://github.com/salk31/RedQueryBuilder bug report here?
NB Should be "IN" not "="

FusionCharts--Unable to find the container DOM Element

Hello guys Im doing a eval on this FusionCharts and I keep running into snags. I get this error and not sure why...anybody out there familiar with FusionCharts??
Im just trying to run the example
<script src="../js/fusioncharts/FusionCharts.js" type="text/javascript"></script>
<script type="text/javascript">
<!--
var myChart = new FusionCharts ( "../js/fusioncharts/Column3D.swf",
"myChartId", "400", "300", "0", "1" );
myChart.setJSONData( {
"chart":
{
"caption" : "Weekly Sales Summary" ,
"xAxisName" : "Week",
"yAxisName" : "Sales",
"numberPrefix" : "$"
},
"data" :
[
{ "label" : "Week 1", "value" : "14400" },
{ "label" : "Week 2", "value" : "19600" },
{ "label" : "Week 3", "value" : "24000" },
{ "label" : "Week 4", "value" : "15700" }
]
} );
myChart.render("div_view");
// -->
</script>
<div id="div_view">FusionCharts will load here!</div>
Fixed it....FusionCharts will load here!
has tobe BEFORE the JS
When creating the FusionCharts object the fifth parameter is the DOM Element where the rendering should be done see here for more info
http://www.fusioncharts.com/dev/api/fusioncharts.html
As such whatever string you have there as the DOM element should be set as the id of the DIV where you want the chart to be displayed, for example:
The Fusion chart object is created like this : $pie3dChart = new FusionCharts("pie3d", "ex2", "100%", 400, "chart-1", "json", ....
Here the string "chart-1" is the DOM Element id and so you should have a div in the document like this <div id="chart-1"></div> which will be where the rendering will take place.
By the time fusion charts are loaded, the dom is not yet loaded completely.
so try the scripting with
$(document).ready(function(){
// your code goes here.
var myChart = new FusionCharts ( "../js/fusioncharts/Column3D.swf",
"myChartId", "400", "300", "0", "1" );
myChart.setJSONData( {
"chart":
{
"caption" : "Weekly Sales Summary" ,
"xAxisName" : "Week",
"yAxisName" : "Sales",
"numberPrefix" : "$"
},
"data" :
[
{ "label" : "Week 1", "value" : "14400" },
{ "label" : "Week 2", "value" : "19600" },
{ "label" : "Week 3", "value" : "24000" },
{ "label" : "Week 4", "value" : "15700" }
]
} );
myChart.render("div_view");
});
otherwise.
write the script tag after the <div> tag

Categories

Resources