get json specific value in javascript from json file - javascript

I have a json.json file like this
{"name1":"Hallo","name2":"Defy","name3":"Carm","name4":"Disney"}
And this script im using to read the file
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
$.each(person, function(key, value)
{document.write(key+"= "+value+"<br />");
});
});
});
</script>
This script is made to poin out all of the data but i need only "name3" value to be stored to +value+
How to do that?

You dont need to iterate then:
$.getJSON("json.json", function(person){
document.write("name3=" person.name3);
});
I'd probably stray away from document.write and append to a container.
<div id="test"></div>
$.getJSON("json.json", function(person) {
$("#test").append("<span> name3= " + person.name3 + </span>");
});

$.getJSON provides the JavaScript object that is represented by the JSON it retrieves.
To access the name3 property of the object, as with any JavaScript Object, you can simply do:
$.getJSON("json.json", function(person){
// do whatever you want with person.name3...
console.log(person.name3);
}

To access to the property you just have to use " . ", so to get the name3 you have to do value.name3
There's no no need to use a foreach if you only have 1 item
<script type='text/javascript'>
$(window).load(function(){
$.getJSON("json.json", function(person){
document.write(key + " = " + value.name3 + "<br />");
});
});
</script>

Related

Asp.net mvc passing a C# model to Javascript file

I want to pass the value i got it from model to the java-script function
<script type="text/javascript">
var checkin = #Model.Parameters.Checkin.ToString("dd-MM-yyyy");
var checkout = #Model.Parameters.Checkout.ToString("dd-MM-yyyy");
</script>
this function that i want to pass model chick-in and chick-out value to it:
$('document').ready(function () {
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
i tried many solution but it didn't work yet .
any advice, thanks
if the #Model.Parameters.Checkin and #Model.Parameters.Checkout not null then Try:
<script type="text/javascript">
$( document ).ready(function(){
var checkin = '#Model.Parameters.Checkin.ToString("dd-MM-yyyy")';
var checkout = '#Model.Parameters.Checkout.ToString("dd-MM-yyyy")';
$("#Arrival").val(checkin);
$("#Departure").val(checkout);
});
Just you miss '. and also change $('document').ready(function () { }) to $(document).ready(function () { }).
you must write all script into a .cshtml file. #Model.Parameters.Checkin.ToString("dd-MM-yyyy") never work into a .js file.
Because, In .cshtml, when the the page is render then it white to HTTP response stream as a string.
In MVC, you can use following code:
<script type="text/javascript">
var number = parseInt(#ViewBag.Number); //Accessing the number from the ViewBag
alert("Number is: " + number);
var model = #Html.Raw(#ViewBag.FooObj); //Accessing the Json Object from ViewBag
alert("Text is: " + model.Text);
</script>

Parsing json from external url Html and JS only

<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link="http://mywp.com/cilacap/api/get_posts/";
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id' ';
</script>
</html>
It only shows "hi".
Can someone tell me how to show JSON items such as "id" and "postDate"
with looping but without PHP scripting?
Thanks
Few syntactical errors, below is the right one.
<html>
<body>
<div id="output">hi</div>
</body>
<script>
var link='{"url":"http://mywp.com/cilacap/api/get_posts/", "id":"url_id_01"}';
var jcontent= JSON.parse(link);
var output=document.getElementById('output');
output.innerHTML=jcontent.id + ' ';
</script>
</html>
JSON Data(var link), was not parsable.
JSON Data(var link), didnt contained any attribute called id.
String concatenation in last line(output.innerHTML), was wrong.
Try removing the quotes from:
output.innerHTML=jcontent.id' ';
and change it to:
output.innerHTML += jcontent.id;
Providing that the link is valid it should work now.
You can also write:
console.log(jcontent);
and check if the console displays the value, or any errors that have occurred.
That url is a string, not json.
Use Ajax to get the data ( using jquery)
var link;
$.ajax({
url: "test.html",
}).done(function(data) {
link = data;
});
Then, extract the data;
output.innerHTML=jcontent.id;
Is for the value. You get the key like this:
ES7
Object.entries(jcontent)
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES6
Object.keys(jcontent)
.map(key => [key, jcontent[key]])
.forEach(keyValuePair =>
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
ES5 (Most likely your case)
Use function instead of arrow functions for es5:
Object.keys(jcontent)
.map(function(key){ [key, jcontent[key]] })
.forEach(function(keyValuePair)
{
// Push to HTML
var t = document.createTextNode(keyValuePair[0] + ' : ' + keyValuePair[1]);     // Create a text node
output.appendChild(t);   
});
Access the value:
keyValuePair[0] // key
keyValuePair[1] // value
Ps
If you want to use the es7 or es6 method, have a look at babeljs

My for in loop output fork fails

I'm looking at this "for in" tutorial and I don't understand why I can't get the loop to write the aProperty value instead of just its name.
http://www.tutorialspoint.com/cgi-bi...=javascript_15
I've tried:
document.write(navigator.aProperty);
document.write(navigator + . + aProperty);
And various other forms, all have failed.
If I just code
document.write(navigator.onLine);
Why can't I make the var, "aProperty" work as a document.write parameter?
Thanks!
<script type="text/javascript">
<!--
var aProperty;
document.write("Navigator Object Properties<br /> ");
for (aProperty in navigator)
{
document.write(aProperty);
document.write("<br />");
}
document.write("Exiting from the loop!");
//-->
</script>
</body>
</html>
aProperty is, indeed, just the key. to return the value you need to ask navigator for it.
Add this in your for...in loop:
for (aProperty in navigator)
{
document.write(navigator[aProperty]);
document.write("<br />");
}

Javascript Help Passing Data via URL

Hi I wonder if someone could help me with this small issue I have the following code which I need to modify.
<script type="text/javascript">
function code(id) {
$('#myStyle').load('myphp.php?id=' + id);
}
</script>
I need to pass another variable into this code and add it to the GET part of the URL for example above it will include the URL myphp.php?id=124545
I want to add a second variable called num to the URL part but am confused what the code will need to become to make the correct post via GET
<script type="text/javascript">
function code(id,num) {
$('#myStyle').load('myphp.php?id=' + id); // how do I add the &num=124 for example
}
</script>
Thanks in advance
Simple. Use:
$('#myStyle').load('myphp.php?id=' + id + '&num=' + num);
Reference: http://www.quirksmode.org/js/strings.html#conc
Hope it helps!
Concatenate "&num="+num onto the string you already have:
<script type="text/javascript">
function code(id,num) {
$('#myStyle').load('myphp.php?id=' + id + "&num=" + num); // how do I add the &num=124 for example
}
</script>

How to reload JSON with AJAX every 10 Seconds

I'm trying to reload a JSON file every 10 seconds with JQUERY.
The page is here: http://moemonty.com/chirp/chirp.html
The Code is here:
<html>
<head>
<title>the title</title>
<!-- included Jquery Library -->
<script type="text/javascript" src="./js/jquery-1.4.2.js"></script>
<!-- jquery library -->
</head>
<body>
<script>
$.ajaxSetup({ cache: false }); //disallows cachinge, so information should be new
function loadChirp(){ //start function
var url = "http://www.chirpradio.org/json";
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data){
console.log(data.query.results.json);
document.write('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
document.write('The artist is: ' + data.query.results.json["record-label"] + '<br/><br/>' );
document.write('The album is: ' + data.query.results.json.album + '<br/><br/>');
document.write('The record label is: ' + data.query.results.json["record-label"] + '<br/><br/>');
document.write('The feedback link is: ' + data.query.results.json["feedback-link"] + '<br/><br/>');
document.write('The database id is: ' + data.query.results.json["database-id"] + '<br/><br/>');
document.write('The time is: ' + data.query.results.json.timestamp.time + ' ');
document.write(data.query.results.json.timestamp["am-pm"] + '<br/><br/>');
document.write('The current dj is: ' + data.query.results.json["current-dj"] + '<br/><br/>');
setTimeout("loadChirp()",5000);
alert('The timeout was triggered.');
});
} //end function
$(document).ready(function(){
//DOCUMENT READY FUNCTION
loadChirp();
});
//DOCUMENT READY FUNCTION
</script>
</body>
</html>
It doesn't seem to be working.
You probably want the previous set of returned data replaced by the new set, instead of appending it. In that case, using jQuery you can do:
<div id='content'></div>
<script>
function loadChirp(){
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22"+url+"%22&format=json&callback=?",
function(data) {
$('#content').html('The artist is: ' + data.query.results.json.artist + '<br/><br/>');
});
setTimeout("loadChirp()",5000);
}
</script>
etc...
I would expect the loop to work as quoted, but there could be a subtlety around the fact you're using JSONP. I would change the setTimeout call to:
setTimeout(loadChirp, 5000);
...for a couple of reasons. First off, using the function reference rather than a code string is a better idea generally, and second off, you're quite certain that you're getting the right function reference (whereas with the string, what reference you get depends on the context in which the code is executed).
But as Pointy pointed out in a comment, there's a separate issue: document.write will not do what you probably want it to do there. You can only use document.write to write to the HTML stream that's being parsed as part of the original page load. After the page load, you can't use it anymore. Consider using jQuery's append or appendTo and similar functions to add to the DOM after page load.
You have an error in console.log(data.query.results.json); - console is not defined.
Also, you can use setInterval( "function()", 5000 );.
You should definitely use:
setInterval("loadChirp", 10000):
Don't write loadCrirp() inside setInterval as we're only passing a refrence

Categories

Resources