Parse JSON from local url with JQuery - javascript

I have a local url where i can retrieve a json file. I also have a simple website which is build using JQuery.
I've looked up many sites for tutorials and sample code on how to retrieve the json input and parse it so i can display it on my site. However non were helpful as i still can't make it work.
So as a last resort i'm going to ask stackoverflow for your help. I have a lot of java knowledge, but I'm relative new to 'web'-development and know some basics of javascript.
This is a sample output of my url:
[
{
"baken": "not implemented...",
"deviceType": "Optimus 2X",
"batteryLevel": "1.0",
"gps": {
"speed": 0,
"Date": "TueNov0100: 34: 49CET2011",
"Accuracy": 35,
"longitude": {removed},
"latitude": {removed},
"Provider": "gps"
},
"deviceId": "4423"
},
{
"baken": "notimplemented...",
"deviceType": "iPhone",
"batteryLevel": "30.0",
"gps": {
"speed": 0,
"Date": "TueNov0116: 18: 51CET2011",
"Accuracy": 65,
"longitude": {removed},
"latitude": {removed},
"Provider": null
},
"deviceId": "4426"
}
]
Hope you can help me..

If you are running a local web-server and the website and the json file are served by it you can simply do:
$.getJSON('path/to/json/file.json', function(data) {
document.write(data);
})
If you are just using files and no webserver you might get a problem with the origin-policy of the browser since AJAX request cannot be send via cross-domain and the origin domain is 'null' per default for request from local files.
If you are using Chrome you can try the --allow-file-access-from-files parameter for developing purposes.

Your URL returns invalid json. Try pasting it in jsonlint.com and validating it there and you'll see what I mean. Even the code highlighting here on stackoverflow is showing you what's wrong. :)
Edit: To parse it you can use jQuery.parseJSON
jQuery.parseJSON('{"foo": "goo"}');

$.get('/some.json', function(data) {
// data[0]["baken"] == "not implemented..."
});
See http://api.jquery.com/jQuery.get/

You don't need to parse the json -- that is why people like it. It becomes a native JavaScript object.
For your example if you put the results in a variable called data then you could do things like this:
data[0].deviceType // would be "Optimus 2x"
data[0].gps.speed // would be numeric 0
etc.

The most natural way is to allow jQuery to make an AJAX call for you once you've already entered the page. Here's an example:
$.ready(function() {
// put your other code for page initialization here
// set up a global object, for namespacing issues, to hold your JSON.
// this allows your to be a good "web" citizen, because you will create
// one object in the global space that will house your objects without
// clobbering other global objects from other scripts, e.g., jQuery
// makes the global objects '$' and 'jQuery'
myObjects = {};
// start JSON retrieval here
$.getJSON('/path/to/json/file.json', function(data) {
// 'data' contains your JSON.
// do things with it here in the context of this function.
// then add it to your global object for later use.
myObjects.myJson = data;
});
});
The API documentation is here

Related

Need to print data from an xml response in postman?This xml is a bit strange one

1.I need to do api testing.
2.Here is the xml response given by the server.
3.I need to extract the data of partID,partBrand,quantityAvailable and store it
in an environment variable's and also print it in console.
4.I'm using Postman tool in chrome and used java
script code to perform some tests.
5.Please provide a solution to extract data from this xml.
<Reply
xmlns="">
<productID>G500</productID>
<ProductVariationInventoryArray>
<ProductVariationInventory>
<partID>B11007514</partID>
<partDescription>g500 BLACK M</partDescription>
<partBrand>Gildan</partBrand>
<quantityAvailable>72105</quantityAvailable>
<attributeColor>BLACK</attributeColor>
<attributeSize>M</attributeSize>
<validTimestamp>2017-11-23T05:31:39.689-05:00</validTimestamp>
</ProductVariationInventory>
</ProductVariationInventoryArray>
</Reply>
Here is the code after converting it to json object using "xml2Json(responsebody)"
{
"Reply": {
"productID": "G500",
"ProductVariationInventoryArray": {
"ProductVariationInventory": {
"partID": "B11007514",
"partDescription": "g500 BLACK M",
"partBrand": "Gildan",
"quantityAvailable": "72105",
"attributeColor": "BLACK",
"attributeSize": "M",
"validTimestamp": "2017-11-23T05:31:39.689-05:00"
}
}
}
}
Now,I need to extract the data of partID,partBrand,quantityAvailable and store it in an environment variable's and also print it in console.

How to add object to external JSON file with a button-click?

Goodday fellow programmer,
I'm having trouble adding an object to my JSON file. I'm using jQuery.
My javascript file:
$('#addchallenge').click(function()
{
//hardcoded challenge
var addchallenge =
{
"achievementname": "I am an achievement who want to be added to the list",
"points": "50",
"comment": "guess who has been a nasty achievement to add"
}
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function ()
{
//very suspicious line here:
this["achievementlist"].push(addchallenge);
});
});
});
My external JSON file:
{
"allachievements":[
{
"name": "list of all achievements",
"achievementlist": [
{
"achievementname": "first achievement",
"points": "30",
"comment": "the first achievement to achieve"
},
{
"achievementname": "second achievement",
"points": "-90",
"comment": "is worth a negative amout of points"
},
{
"achievementname": "aaand the 3th achievement",
"points": "30",
"comment": "do you already have achievement 1 and 2?"
}]
}]
}
How could the addchallenge data be added into my JSON file?
Do I need to parse my JSON data, add my challenge to add, then stringify it back?
Thanks in advance :)
You cant directly manipulate the JSON file - Writing, deleting etc.
However, you could write some backend code thats capable of this.
If you simply want to temporally add an achievement, you can parse in your JSON file into a variable and then manipulate it.
You can't modify the JSON file only with client side code. You need some server side code.
I would recommend you to use post().
EDIT:
I actually found this: How to : edit an external json file in javascript
So, current post may be considered a duplicate...
Are you trying to write into a file using jquery?
if so please check the following url:
Read/write to file using jQuery
Your problem is this, the context. Inside of the callback you are passing to $.each iterator, this is not what you think it is.
jQuery.each( array, callback )
callback
Type: Function( String propertyName, Object valueOfProperty )
The function that will be executed on every object.
I would change your code like this:
$.getJSON("../json/package.json", function (data)
{
$.each(data.allachievements, function (key, value)
{
value["achievementlist"] = value["achievementlist"] || [];
value["achievementlist"].push(addchallenge);
});
});

How Do I See the Output of Changes to JSON

Updated to try to be more clear given the comments (Thank you for comments)
I apologize in advance for this question. I may just not have the vocabulary to properly research it. If I have an array of objects called restaurants stored in my project, for example:
restaurants: [
{
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I then run a function to add a unique idea to all the objects in the array. The result of console.log(restaurants) is this:
{
"id": 3472,
"name": "joes's pizza",
"url": "joespizza.com",
"social properties": {
"Facebook":"fb.com/pizza",
"Instagram":"instagram.com/pizza",
"googlePlus":"pizza+",
"Twitter":"twitter.com/pizza"
}
},
{
"id": 9987,
"name": "tony's subs",
"url": "tonys.com",
"social properties": {
"Facebook":"fb.com/subs",
"Instagram":"instagram.com/subs",
"googlePlus":"subs+",
"Twitter":"twitter.com/subs"
}
},
{....}
]
I would now like to have this updated array of objects available to look at in my project, via the text editor, as a variable or restaurants.json file. How do I actually see the new modified json array and how do i save it so that i can work with it the same way i did this one above? I am currently doing this in the browser. I can see the results if i log it to the console but I need to be able to work with the new output. Thanks for taking the time to answer.
You can encode/decode JSON with JSON.stringify() and JSON.parse().
Aside from converting to/from JSON, you work with standard JS objects and arrays:
var array = JSON.parse(json_str);
array[0].address = "5th Avenue";
console.log(JSON.stringify(array));
Well, there's really not enough information in your question but I assume a few things:
You've loaded the json data from somewhere and it has been turned into a javascript object.
You've edited the object somehow and wish to convert it back to json and save the changes.
Assuming the above to be true, you just need to serialize the object back to json and submit it back to your server where you can save it in any manner you deem appropriate.
You can serialize the javascript object with JSON.stringify() (see https://stackoverflow.com/a/912247/4424504)
Add the serialized json to a hidden field on the form and submit it.
On the server when processing the form submission, grab the data from the hidden field and do with it what you wish.
Or get it back to the server any way you wish (ajax call, whatever) the key point is to serialize the object to a json string and save it
Hope that helps...

Parsing JSON data from a Website

I have quite a few questions since I'm relatively new at javascript. I started writing this application that lets the user get stock information from the yahoo finance web service and display it on the website. Sounds easy right? I thought so too but I'm having a hard time manipulating the data I'm getting back. Maybe someone can help me get this working. I feel like I'm really close at this point.
The user enters their stock of choice in the stockTextBox such as AAPL or GOOG. Then I set a script attribute with concatenation. Now the confirm() line is VERY odd. If I don't have that confirm in there the alert in the function myCallBack doesn't seem to execute. I can't explain this at all. Maybe I don't now something I should.
Now if I debug I can tell for a back that stock information is coming back from the website. First here is the code and then the JSON data. I would sincerely appreciate it if anyone could help me get this thing to work. I've been fiddling with it for a couple of hours now. THANK YOU! In other words, my question is how do I go about display data that I got from a web service onto my web page?
<form id="stockInput">
Stock Name: <input type="text" id="stockTextBox">
<input type="submit" id="submitButton" value="Submit">
</form>
</b>
<label id="stockLabel"></label>
<script>
var submitButton = document.getElementById("submitButton");
submitButton.addEventListener('click', actionPerformed, false);
function actionPerformed(e)
{
var textValue = document.getElementById("stockTextBox").value;
//tried to put to an element and then read the element value down below through concatenation in the src...
//document.getElementById("stockLabel").innerHTML = textValue;
var script = document.createElement('script');
script.setAttribute('src',"http://finance.yahoo.com/webservice/v1/symbols/"+textValue+"/quote?format=json&callback=myCallBack");
document.body.appendChild(script);
confirm(); //ODD POINT...
}
function myCallBack(data)
{
alert("HEY" + data);
//What I thought I would do. This doesn't output the right info.
//for(key in data)
//{
//alert(data[key]);
//}
}
</script>
</body>
</html>
Now here is the JSON that I can see in the debugger via Firefox:
myCallBack({
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [{
"resource": {
"classname": "Quote",
"fields": {
"name": "Google Inc.",
"price": "1030.579956",
"symbol": "GOOG",
"ts": "1383249600",
"type": "equity",
"utctime": "2013-10-31T20:00:00+0000",
"volume": "1640035"
}
}
}
]
}
});
You are only seeing [object] because it's displaying the data type. You need to get object attributes to obtain the data. The JSON data is very accessible from javascript seeing as how JSON stands for JavaScript Object Notation.
It's very simple once you get started, as the data is basically comprised of objects with attributes and lists of objects. the variable data is your root object, and you can access everything below it easily.
I'll provide a few examples of how you would access certain things in the data:
the attribute "name":
alert(data.list.resources[0].resource.fields.name);
the attribute "classname":
alert(data.list.resources[0].resource.classname);
It's just a text representation of Javascript objects. "resources" is a list of objects, "list" is an object, "fields" is an object, and "price" is a key/value pair to store data.
Read more here: http://www.json.org/
http://www.w3schools.com/json/
If I misunderstood the question let me know, I took a shot at what I thought you meant.
Treat the JSON object like a regular Javascript object. For instance, if you wanted to display the company name and price:
function myCallBack(data)
{
alert("Name: " + data.list.resources[0].resource.fields.name);
alert("Price: " + data.list.resources[0].resource.fields.price);
}
To display the whole thing in raw form for debugging purposes, you can convert it back into a JSON-serialized string:
function myCallBack(data)
{
alert(JSON.stringify(data));
}
More about JSON: https://developer.mozilla.org/en-US/docs/JSON

How to translate Solr JSON response into HTML while JSON is different every time

I am using Solr 4 for searching in a java web application.Solr produces a JSON response from which i have to extract search results and translate them into html so user can read that.
I know one solution but it seems dumb an I think there must be intelligent ideas.
{
"responseHeader": {
"status": 0,
"QTime": 0,
"params": {
"fl": "id,title",
"indent": "true",
"q": "solr",
"wt": "json"
}
},
"response": {
"numFound": 3,
"start": 0,
"docs": [
{
"id": "1",
"title": "Solr cookbook"
},
{
"id": "2",
"title": "Solr results"
},
{
"id": "3",
"title": "Solr perfect search"
}
]
}
}
After that i eval this text as:
var obj = eval ("(" + txt + ")");
To generate html page i can use either
<script>
document.getElementById("id").innerHTML = obj.response.docs[1].id
document.getElementById("title").innerHTML = obj.response.docs[1].title
</script>
or
document.write(obj.response.docs[1].id);
But limitation is that every time solr gives response with different object structure i.e. an object may have age feild but other can not have because it depends on query.
I want to use a sigle JSP page to display search results(like Google)
for all search queries
is it possible to write a single code segment which works for any possible search results with different schema.
Javascript stops working after encountering any error which is likely in my case. that's also problem.if I use for loop to traverse the object hierarchy it is highly error -prone.
Is it possible with a single view page Thanks.
You might want to consider using ajax-solr - A JavaScript framework for creating user interfaces to Solr
I suggest using Velocity templating which is readily supported in Solr - instead of extracting data from the JSON and rendering the HTML via JS.
Docs here

Categories

Resources