JavaScript: Remove Double Quotes - JSON.Stringify() - javascript

After using he JSON.stringify() method in JavaScript to allow JSON data render in the browser it outputs double quotations " " at either end of the property rendered in the browser - any idea how to resolve this?
Here is my code -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = "<ul class='list'><li>" + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + "</li></ul>";
var myContainer = JSON.stringify(myContainer);
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
</script>

Because "<ul class='list'><li>Faye Garrett - brown</li></ul>" is not a valid JSON string.
Uncomment your stringify lines and it works.

Related

How to get this data using the loop?

How do i show all the data by using the loop to display all the data from json to html ?
ATM , I am able to print one of the data. but if i am using data[i] the code will not display any data.
I think I mess up the the concept of object and array.
please advice me , how to loop thru object , like array?
thanks
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET','https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function () {
var weatherData = JSON.parse(requestWeather.responseText);
console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data.weather ){
var x= data.weather[i].main;
weatherString+= "<p class='weather'>" + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
to get all data check for object and do recursive loop
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
//console.log(weatherData);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for(var i in data) {
var x = data[i];
if(typeof(x) == "object") {
getHTML(x);
}
else {
weatherString += "<p class='weather'><b>" + i + "</b>: " + x + "</p>";
// weatherString+= "<p>" + data.currently.summary + "</p>";
// console.log(data[i].city);
}
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
var getWeather = document.getElementById('weather');
var requestWeather = new XMLHttpRequest();
//+'-31' +'&lon='+'150'
requestWeather.open('GET', 'https://fcc-weather-api.glitch.me/api/current?lat=-31&lon=150');
requestWeather.onload = function() {
var weatherData = JSON.parse(requestWeather.responseText);
getHTML(weatherData);
};
requestWeather.send();
function getHTML(data) {
var weatherString = "";
for (var i in data.weather) {
var x = data.weather[i].main;
weatherString += "<p class='weather'>" + x + "</p>";
$.each(data.main, function(i, f) {
var main = "<div>" + i + ": " + f + "</div>";
$(main).appendTo("#main");
});
}
getWeather.insertAdjacentHTML("beforeend", weatherString);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="weather"></div>
<div id="main"></div>
use foreach loop to iterate over all object
read more from here

JavaScript / JSON Linked Listview - Loading a New Panel

I am trying to write some JavaScript code to load JSON from a URL and then display it in a linked listview that navigates to a new panel within the webapp that I am creating. I have successfully rendered the listview from the JSON data however, I cannot seem to get a new panel open. Any ideas? My code so far it below -
<li class="divider">Brown Eyes</li>
<div id="output1"></div>
<li class="divider">Green Eyes</li>
<div id="output2"></div>
<script>
var myContainer = "";
var panel_view = "";
var a = new XMLHttpRequest();
a.open("GET", "https://api.myjson.com/bins/1dwnm", true);
a.onreadystatechange = function () {
console.log(a);
if (a.readyState == 4) {
var obj = JSON.parse(a.responseText);
for (i = 0; i < obj.length; i++) {
if (obj[i].eyeColor == 'brown') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output1').innerHTML += myContainer;
}
if (obj[i].eyeColor == 'green') {
var myContainer = '<ul class="list"><li><a href="#item_profiles'+i+'" class="icon pin">' + obj[i].name.first + " " + obj[i].name.last + " - " + obj[i].eyeColor + '</li></ul>';
document.getElementById('output2').innerHTML += myContainer;
}
}
}
}
a.send();
panel_view += '<div class="panel" data-title="'+obj[i].name.first+'" id="item_profiles'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+obj[i].name.first+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+obj[i].name.first+'</p></div>';
$('#profiles_panel').after(panel_view);
</script>
EDITED -
So, the purpose of this is to achieve the below code to use just Native JavaScript as oppose to jQuery. Here is the jQuery version of the code -
<script type="text/javascript">
$(document).ready(function () {
var panel_view_admissions = "";
$.getJSON( 'http://localhost:3000/admissions', function(data) {
$.each( data, function(i, name) {
$('ul.list-admissions').append('<li>'+name.title+'</li>');
panel_view_admissions += '<div class="panel" data-title="'+name.title+'" id="item_admissions'+i+'" data-footer="none"><img src="http://localhost:3000/uploads/'+name.image+'" style="width:100%;height:auto;"><p style="padding-left: 10px; padding-right: 10px;">'+name.content+'</p></div>';
});
$('#admissions_panel').after(panel_view_admissions);
});
});
</script>

Get json data based on url

I have a problem with getting the specific data based on my id.
This is my main html.
<div class="container">
<div class="row">
<div class="col-md-12">
<button id="btn">Button</button>
<br>
<div id="id01"></div>
</div>
</div>
</div>
This is my main js
var btn=document.getElementById("btn");
btn.addEventListener("click", function(){
var ourRequest = new XMLHttpRequest();
var url = "url.../incident";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
});
function myFunction(response) {
var arr = JSON.parse(response);
var out = "<table>";
for(i = 0; i < arr.length; i++) {
out += "<tr><td>" +
arr[i].Address +
"</td><td><a href='lista.html?id="+arr[i].ID+"'>" +
arr[i].ID +
"</a></td><td>" +
arr[i].Category +
"</td></tr>";
}
out += "</table>";
document.getElementById("id01").innerHTML = out;
}
This will show me only three data.
this is my lista.html
<div class="container">
<div class="row">
<div class="col-md-12">
<div id="id02">
</div>
</div>
</div>
And this is my js for my lista.html.
var ourRequest = new XMLHttpRequest();
var url = "url../incident?id=";
contentType="applicaton/json; charset=utf-8";
method="GET";
dataType= "json";
ourRequest.onreadystatechange=function()
{
if (this.readyState == 4 && this.status == 200) {
myFunction(this.responseText);
}
}
ourRequest.open("GET", url, true);
ourRequest.send();
function myFunction(response)
{
var arr = JSON.parse(response);
var out = "<table>";
out +="<tr><td>" +
arr.Address +
"</td><td>" +
arr.CaseID +
"</td><td>" +
arr.Category +
"</td><td>" +
arr.Date +
"</td><td>" +
arr.Description +
"</td><td>" +
arr.ID +
"</td><td>" +
arr.InputDate +
"</td><td>" +
arr.Latitude +
"</td><td>" +
arr.Longitude +
"</td><td>" +
arr.ReportedBy +
"</td><td>" +
arr.Subcategory +
"</td><td>" +
arr.Time +
"</td></tr>"
out += "</table>";
document.getElementById("id02").innerHTML = out;
}
So when I click on that arr[i].ID it should send me to th lista.html with the specific ID and specific data.
For example if i click on ID=1, the url look like lista.html?id=1, but nothing shows.
Just pass the id to the request url if the api you send request to expects that
var url = "url?id={your id here}"
In your table you have to use arr.Address instead of response.Address, since the arr is the parsed json object.
You can use console.log to see if the data you need is really there:
function myFunction(response) {
var arr = JSON.parse(response);
console.log(arr);
}
You don't need to read the location href with jQuery, since you already know the id of the request you sent!
So My mistake was like this instead of :
var url = "url../incident?id=";
I should have written :
var url = "url../incident?id="+getQueryVariable("id");
And write this function in the end of my js for my lista.html
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}

Only show objects in array that contain a specific string

I was trying to make something where you can type a string, and the js only shows the objects containing this string. For example, I type Address1 and it searches the address value of each one then shows it (here: it would be Name1). Here is my code https://jsfiddle.net/76e40vqg/11/
HTML
<input>
<div id="output"></div>
JS
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
var restoName = [], restoAddress = [], restoRate = [], restoImage= [];
for(i = 0; i < data.length; i++){
restoName.push(data[i].name);
restoAddress.push(data[i].address);
restoRate.push(data[i].rate);
restoImage.push(data[i].image);
}
for(i = 0; i < restoName.length; i++){
document.getElementById('output').innerHTML += "Image : <a href='" + restoImage[i] + "'><div class='thumb' style='background-image:" + 'url("' + restoImage[i] + '");' + "'></div></a><br>" + "Name : " + restoName[i] + "<br>" + "Address : " + restoAddress[i] + "<br>" + "Rate : " + restoRate[i] + "<br>" + i + "<br><hr>";
}
I really tried many things but nothing is working, this is why I am asking here...
Don't store the details as separate arrays. Instead, use a structure similar to the data object returned.
for(i = 0; i < data.length; i++){
if (data[i].address.indexOf(searchedAddress) !== -1) { // Get searchedAddress from user
document.getElementById("output").innerHTML += data[i].name;
}
}
Edits on your JSFiddle: https://jsfiddle.net/76e40vqg/17/
Cheers!
Here is a working solution :
var data = [{"image":"http://www.w3schools.com/css/img_fjords.jpg","name":"Name1","address":"Address1","rate":"4.4"},
{"image":"http://shushi168.com/data/out/114/38247214-image.png","name":"Name2","address":"Address2","rate":"3.3"},
{"image":"http://www.menucool.com/slider/jsImgSlider/images/image-slider-2.jpg","name":"Name3","address":"Address3","rate":"3.3"}
];
document.getElementById('search').onkeyup = search;
var output = document.getElementById('output');
function search(event) {
var value = event.target.value;
output.innerHTML = '';
data.forEach(function(item) {
var found = false;
Object.keys(item).forEach(function(val) {
if(item[val].indexOf(value) > -1) found = true;
});
if(found) {
// ouput your data
var div = document.createElement('div');
div.innerHTML = item.name
output.appendChild(div);
}
});
return true;
}
<input type="search" id="search" />
<div id="output"></div>

get text from attribute and format it

I have a div elements with data-seat and data-row property:
<div class='selected' data-seat='1' data-row='1'></div>
<div class='selected' data-seat='2' data-row='1'></div>
<div class='selected' data-seat='3' data-row='1'></div>
<div class='selected' data-seat='1' data-row='2'></div>
<div class='selected' data-seat='2' data-row='2'></div>
I want print friendly message for selected seats:
var selectedPlaceTextFormated ='';
$(".selected").each(function () {
var selectedPlace = $(this);
selectedPlaceTextFormated += "Row " + selectedPlace.attr("data-row") + " (seat " + selectedPlace.attr("data-seat") + ")\n";
});
alert(selectedPlaceTextFormated);
This code works well and shows the following:
Row 1 (seat 1)
Row 1 (seat 2)
Row 1 (seat 3)
Row 2 (seat 1)
Row 2 (seat 2)
But, I want group seats by row, i.e I want the following:
Row 1(seats: 1,2,3)
Row 2(seats: 1,2)
also, order by row number. How can I do this?
Thanks. DEMO
Here is the code
var selectedPlaceTextFormated ='';
var row_array = [];
$(".selected").each(function () {
var selectedPlace = $(this);
if (!row_array[selectedPlace.attr("data-row")]){
row_array[selectedPlace.attr("data-row")] = selectedPlace.attr("data-seat");
}
else row_array[selectedPlace.attr("data-row")] += ','+selectedPlace.attr("data-seat");
});
for (row in row_array){
alert("Row "+ row +"(seat " + row_array[row] + ")\n" );
}
And here the link to the working fiddle: http://jsfiddle.net/3gVHg/
First of all, jQuery is kind enough to automatically grab data- attributes into its data expando object, that means, you can access those data via:
jQueryObject.data('seat');
for instance.
Your actual question could get solved like
var $selected = $('.selected'),
availableRows = [ ],
selectedPlaceTextFormated = '',
currentRow,
currentSeats;
$selected.each(function(_, node) {
if( availableRows.indexOf( currentRow = $(node).data('row') ) === -1 ) {
availableRows.push( currentRow );
}
});
availableRows.forEach(function( row ) {
selectedPlaceTextFormated += 'Row ' + row + '(';
currentSeats = $selected.filter('[data-row=' + row + ']').map(function(_, node) {
return $(this).data('seat');
}).get();
selectedPlaceTextFormated += currentSeats.join(',') + ')\n';
});
jsFiddle: http://jsfiddle.net/gJFJW/3/
You need to use another variable to store the row, and format accordingly.
var selectedPlaceTextFormated ='';
var prevRow = 0;
$(".selected").each(function () {
var selectedPlace = $(this);
var row = selectedPlace.attr("data-row");
var seat = selectedPlace.attr("data-seat");
if(prevRow == row){
selectedPlaceTextFormated += "," + seat;
}
else{
if(selectedPlaceTextFormated != ''){
selectedPlaceTextFormated += ')\n';
}
selectedPlaceTextFormated += "Row " + row + " (seat " + seat;
prevRow = row;
}
});
selectedPlaceTextFormated += ')\n';
alert(selectedPlaceTextFormated);
Check http://jsfiddle.net/nsjithin/R8HHC/
This can be achieved with a few slight modifications to your existing code to use arrays; these arrays are then used to build a string:
var selectedPlaceTextFormated = [];
var textFormatted = '';
$(".selected").each(function(i) {
var selectedPlace = $(this);
var arr = [];
selectedPlaceTextFormated[selectedPlace.attr("data-row")] += "," + selectedPlace.attr("data-seat");
});
selectedPlaceTextFormated.shift();
for (var i = 0; i < selectedPlaceTextFormated.length; i++) {
var arr2 = selectedPlaceTextFormated[i].split(",");
arr2.shift();
textFormatted += "Row " + (i + 1) + " seats: (" + arr2.join(",") + ")\n";
}
alert(textFormatted);
​
Demo
I'd just do this:
var text = [];
$(".selected").each(function () {
var a = parseInt($(this).data('row'), 10),
b = $(this).data('seat');
text[a] = ((text[a])?text[a]+', ':'')+b;
});
var selectedPlaceTextFormated ='';
$.each(text, function(index, elem) {
if (!this.Window) selectedPlaceTextFormated += "Row " + index + " (seat " + elem + ")\n";
});
alert(selectedPlaceTextFormated);
FIDDLE

Categories