I want to select one specific property of a jason object.
This is the structure of the JSON:
{
"resultsPage:" {
"results": { "event": [
{
"id":11129128,
"type":"Concert",
"uri":"http://www.songkick.com/concerts/11129128-wild-flag-at-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag at The Fillmore (April 18, 2012)",
"start":{"time":"20:00:00",
"date":"2012-04-18",
"datetime":"2012-04-18T20:00:00-0800"},
"performance":[{"artist":{"uri":"http://www.songkick.com/artists/29835-wild-flag?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"Wild Flag","id":29835,"identifier":[]},
"displayName":"Wild Flag",
"billingIndex":1,
"id":21579303,
"billing":"headline"}],
"location":{"city":"San Francisco, CA, US","lng":-122.4332937,"lat":37.7842398},
"venue":{"id":6239,
"displayName":"The Fillmore",
"uri":"http://www.songkick.com/venues/6239-fillmore?utm_source=PARTNER_ID&utm_medium=partner",
"lng":-122.4332937, "lat":37.7842398,
"metroArea":{"uri":"http://www.songkick.com/metro_areas/26330-us-sf-bay-area?utm_source=PARTNER_ID&utm_medium=partner",
"displayName":"SF Bay Area","country":{"displayName":"US"},"id":26330,"state":{"displayName":"CA"}}},
"status":"ok",
"popularity":0.012763
}, ....
]},
"totalEntries":24,
"perPage":50,
"page":1,
"status":"ok"
}
}
This is what I'm doing to get the JSON:
url: "http://api.songkick.com/api/3.0/artists/480448/calendar.json?apikey=APIKEY&jsoncallback=?",
dataType: "jsonp", // <== JSON-P request
success: function (data) {
$.each(data["resultsPage"]["results"]["event"], function (i, entry) {
$("#events").append('<li>' + entry.displayName + '</li>');
});
I'm new with JSON so my question is: How do I get the latitude and longitude of a location by entering an artist name out this JSON object? Any Idea?
You would use entry.location.lng and entry.location.lat inside your $.each() function.
each property, if not an array, can be accessed with dot notation, which most people find easier to read and understand. meaning, your $.each() could also be defined like this :
$.each(data.resultsPage.results.event, function (i, entry) {
Hope that helps...
If you have to match a given property value, then you're going to have to crawl and check for it.
for ( loop events )
if ( select Name = thing you want )
do my stuff
Related
I have a $getJSON() that i want to pass a var through how ever i always get undefined in console log.
I have done this before i just cant seem to figure out why this isnt working.
Any help would be appreciated.
here is my example
{
"harry": {
"example": "test",
"example1": "test",
}
"james": {
"example": "test",
"example1": "test",
}
"ben": {
"example": "test",
"example1": "test",
}
}
var usersidno = $("#hiddenid").html();
$.getJSON(
"http://localhost/example/file.json",
function(json) {
console.log(json.usersidno);
});
<div id="hiddenid">harry</div>
When you want to access an object's (JSON) property dynamically (using a variable or expression), you should use square bracket notation.
[your expression or variable inside square brackets]. i.e, json[useridno]
var usersidno = $("#hiddenid").html();
$.getJSON(
"http://localhost/example/file.json",
function(json) {
console.log(json[usersidno]); // try to use square brackets
});
This is a working example of ,your issue I have used an api ,that gives back a json ,You can use [] annotatiton to access object properties.
$(document).ready(function(){
var user = $("#hiddenid").html()
console.log(typeof user)
$.getJSON(
"https://jsonplaceholder.typicode.com/todos/1",
function(json) {
let js=JSON.parse(JSON.stringify(json))
console.log(js[user]);
console.log(js.user);//undefined
console.log(js)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="hiddenid">userId</div>
Explanation:
var userid = 'userId';
console.log(x.userid); // it looks for x.userid, which throws undefined,if it does'nt exists
console.log(x[userid]); // looks for x['userId'] which it will find
Have a look at mdn docs
I have some complex question.
My first JSON url has this properties, ID, Name and Parameter. Then when I call the JSON, I want to go to retrieve another JSON URL based on the ID to get the child ID.
Then I want to output as Child ID, Parent Name and Parent Parameter.
Here is the jsFiddle http://jsfiddle.net/c3L7gr4w/1/
And here is the model url 1
[
{
"ParemeterValues": "Actual,2011,SYS.LoadCompanies,y,y",
"ID": "1771cdf7-7a73-49e4-8538-0d0cad965226",
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
},
{
"ParemeterValues": "Actual,2012",
"ID": "19439ce4-240c-4f2a-98ee-47cb1708b339",
"Name": "Data.BS.BringForwardOpeningBalances",
}
]
and the model url2
{
"ID": "1771cdf7-7a73-49e4-8538-0d0cad965226",
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
"TM1.ChoreProcessesProcess":
[
{
"Name": "EXEC.Data.PLandBS.FromFMISMultipleCompanies",
"ID": "dd1acc0b-51ff-4844-b6c4-c67640b326c4",
}
]
}
I think you need to adjust your dataMappingOptions.key so that KO can return a different key when you load your child model in on top of your original.
I have a working fiddle here, I think - http://jsfiddle.net/sifriday/c3L7gr4w/4/
dataMappingOptions now looks like:
var dataMappingOptions = {
key: function(data) {
var ChildID = "";
if (data["TM1.ChoreProcessesProcess"] != undefined)
ChildID = data["TM1.ChoreProcessesProcess"][0].ID
return data.ID + ChildID;
},
create: function(options) {
return new Person(options.data);
}
};
The problem with this is that when you load your updatedData KO will now use the mapping to destroy your original people and create new ones. However, updatedData is missing the ParemeterValue, so you need to merge this in from your original JSON. This will be OK even when you are using Ajax, because you can save the original JSON in a variable somewhere:
loadUpdatedData: function() {
// You need to merge in paremeterValues from your orig JSON
updatedData[0].ParemeterValues = data[0].ParemeterValues;
// Now good to go...
ko.mapping.fromJS(updatedData, dataMappingOptions, viewModel.people);
}
(I've also done it so that ChildID is appended as an extra property, but you should be able to see from this how to make it replace the original ID in both the People view-model and in the dataMappingOptions.key)
I have a json file in a folder called json/img_desc.json
Here is the json file
{ "theimages":[
{
"number":1,
"title":"Joy Toy teddy bear",
"description":"In etc etc"
} etc etc
Then I used this code to try and get the first value.
$.getJSON('json/img_desc.json', function(theimages) {
console.log(img_desc.theimages.number[0]);
});
The error
It says this
[15:06:46.951] ReferenceError: img_desc is not defined #
file:///[removed for privacy]/js/puzzle.js:246
it should be
$.getJSON('json/img_desc.json', function (theimages) {
console.log(theimages.theimages[0].number);
//if you want to loop
$.each(theimages.theimages, function (idx, obj) {
console.log(obj.number)
})
});
Documentation says http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- it will pass a plain object as the second parameter. So, you can do something like this
$.getJSON('json/img_desc.json', function(theimages) {
$.each(theimages.theimages, function( index, val ) {
console.log(val, val.number);
});
});
$.getJSON('json/img_desc.json', function(img_desc) {
console.log(img_desc.theimages.number[0]);
});
Should fix your problem. As if you have any other problem, ask it in a separate question.
In page 1 I have this array:
$pole = array("countLike" => "countLike", "Message" => "Some message");
echo json_encode($pole);
And I want get this data on page 2, but this code doesn't work.
function Like(id)
{
$.post("page1.php", { action: "Like", "id": id }, function(data) {
var obj = jQuery.parseJSON(data);
$(".countLike#"+id).html(obj.countLike);
$(".Message#"+id).html(obj.Message);
});
}
Can you help me please with this code.
Thanks.
Pass json as expected output from the post request.
function Like(id)
{
$.post("page1.php", { action: "Like", "id": id }, function(data) {
//data is already a json parsed string
$(".countLike#"+id).html(data.countLike);
$(".Message#"+id).html(data.Message);
}, "json"); // <<<<< This is what you missed
}
Code should work making the request but there is an issue with your element selectors.
".countLike#"+id
".Message#"+id
The "#" is not space separated from the class name. Issue now becomes are you looking for elements with ID "#"+id? I suspect you are so you really don't need the class prefixing the ID at all and simply use
$('#' + id)
An Id selector is far faster for jQuery to search than class since there can only be one in the page.
I've already read those questions but none of them answer to my need:
Testing for an empty array object in JSON with jQuery
jQuery 1.4.4+ AJAX request - post empty array or object becomes string
Cannot access data from jQuery Ajax request, returns empty array
JQuery removes empty arrays when sending
(the latest one said just add hard-coded quotes ie [''] but I can't do this, I'm calling a function that returns an Array)
So here's my code (note that the problem lies to the empty array new Array()):
function AjaxSend() {
$.ajax({
url: '/json/myurl/',
type: 'POST',
dataType: 'jsonp',
data : { 'tab':new Array() },
context: this,
success: function (data) {
if (data.success) {
console.log('ok');
}
else {
console.log('error');
}
}
});
}
Simple eh?
Here's my Php code:
echo '_POST='.var_export($_POST,true)."\n";
And here's the result:
_POST=array (
)
jQuery1710713708313414827_1329923973282(...)
If I change the empty Array by a non-empty, i.e.:
'tab':new Array({ 't':'u' },{ 'v':'w' })
The result is:
_POST=array (
'tab' =>
array (
0 =>
array (
't' => 'u',
),
1 =>
array (
'v' => 'w',
),
),
)
jQuery1710640656704781577_1329923761425(...)
So this clearly means that when there's an empty Array() to be sent, it is ignored, and it's not added to the POST variables.
Am I missing something?
PS: my jQuery version is from the latest google CDN i.e.:
http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js
and
http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js
I want the array to be sent, even if it's empty (= send [])!
Any solution? Any idea? I've already tried to add this option traditional: true without success.
The problem is that you can't really send empty array. Have you tried to send an empty array manually? How would that uri look (note that it's the same reasoning for POST)?
/path?arr[]
This would result in a $_GET like this:
array (
'arr' => array (
0 => ''
)
)
That's not really an empty array, is it? It's an array with a single element of an empty string. So what jQuery does, and I would agree that this is the correct way of handling it, is to not send anything at all.
This is actually really simple for you to check on the server. Just add an extra check whether the parameter exists or not, i.e:
$tabs = array();
if(isset($_POST['tab'])) {
$tabs = $_POST['tab'];
}
Try
php
<?php
// `echo.php`
if (isset($_POST["emptyArray"])) {
function arr() {
$request = $_POST["emptyArray"];
if(is_array($request) && count($request) === 0) {
// do stuff
echo $request;
};
};
arr();
};
js
$.post("echo.php", {"emptyArray":[]}
, function (data, textStatus, jqxhr) {
if (textStatus === "success" && data.length === 0) {
// do stuff
console.log(data.length === 0 ? new Error("error").message : data);
};
});
jsfiddle http://jsfiddle.net/guest271314/Lf6GG/