How to parse a JSON array - javascript

new here and hit a roadblock, been searching but can't find the answer with my skill set. Task is pretty simple, I want to parse this http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json which is from a weather station. I have used the W3C tutorial but just can't seem to parse this file, but http://json.parser.online.fr has no problem. All the looping parse examples just give me alert after alert.
All I want is the ability to select temp[0] (out of god knows how many) for example via javascript and have it display on a website. I'm really lost, tried searching and if I've missed the goldmine then my bad. Thanks!
Example code
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌​43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌​43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj.temp[0];

First, you need to parse the incoming string as below:
temp_arr = JSON.parse(json_string);
Just loop over the temp_arr array, and in each iteration of loop you'll have one object (tobj). For example, like this:
{"humidity":"40.9000","stationtime":"2014-07-06 21:21:03","temp":"22.6000","timestamp":"2014-07-06T11:20:27.231Z"}
All you have to do is, access it like tobj.temp and use it to display on page.
I have written a jquery implementation at: http://jsfiddle.net/DNH5n/2/

Jquery makes working with JSONP much easier heres an example (http://jsfiddle.net/icodeforlove/9mBsr/)
$.getJSON('http://data.sparkfun.com/output/AJ2p4r8Owvt1MyV8q9MV.json?callback=?', function (data) {
data.forEach(function (item) {
$('body').append(JSON.stringify(item));
});
})
update again
heres another example using your code (http://jsfiddle.net/icodeforlove/9mBsr/2/)
var text = '[{"humidity":"42.8000","stationtime":"2014-07-06 19:43:52","temp":"23.3000","timestamp":"2014-07-06T09:44:07.918Z"},{"humidity":"‌43.0000","stationtime":"2014-07-06 19:42:57","temp":"23.2000","timestamp":"2014-07-06T09:42:22.003Z"},{"humidity":"‌43.2000","stationtime":"2014-07-06 19:42:36","temp":"23.3000","timestamp":"2014-07-06T09:42:51.737Z"}]';
var obj = JSON.parse(text);
document.getElementById("demo").innerHTML = obj[0].temp;

Related

Google Spreadsheet Pushing to Array

I'm trying to create a Google sheets script which I hear is complete Javascript so I'm told. I'm just trying to create a list of quests relevant to an item in an online game by parsing the HTML in the spreadsheet.
Example: http://everquest.allakhazam.com/db/item.html?item=14295
Ideally in this case it should bring across the 4 quest names, their location and the quest ID (which can be found within the URL in the source code). But I'm just trying to pull the quest ID at the moment as can be found below.
function myFunction(itemid) {
var regexp = /quest.html\?quest\=(.*)"/;
var page = UrlFetchApp.fetch('http://everquest.allakhazam.com/db/item.html?item=' + itemid).getContentText();
var matches = [];
var number = page.match(/<li><a href="\/db\/quest.html\?quest\=(.*)"/);
for (var i in number) {
matches.push(number[i]);
}
return matches;
}
But the script just seems to hang on 'Loading..' and doesn't do anything. If I add 'return number just after the page.match it returns the first quest ID fine.. so it seems it may be related with pushing to the array which is causing the issues.
It is better not to parse HTML as text. You can use a formula with importxml function to get your data using XPath:
=importxml("http://everquest.allakhazam.com/db/item.html?item=14295";"//div[#id='quest']//b|//div[#id='quest']/ul/li/a|//div[#id='quest']/ul/li/a/#href")

Javascript, Lodash, Underscore change value of Array

May be a duplicate but read alot on here on how to achieve the following and couldn't get it to do exactly what I need. Read: Javascript array Link2 link3
I have a large array (short sample provided below) and would like to format the REPORT_DATE value so that instead of for example "31/05/2015 00:00:00" I get 31/05/2015. Does anyone know of an easy way to do this ?
{["data":[{"DOC1":"1234","FILE_NAME":"4321.PDF","TITLE":"gwewrgw","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"1234512","CLIENT_NAME":"Zuba"}
,{"DOC1":"4737","FILE_NAME":"52345.PDF","TITLE":"erywery","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"5234523","CLIENT_NAME":"Ziba"}
,{"DOC1":"1234","FILE_NAME":"452345.PDF","TITLE":"wgrwrg","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"23452345","CLIENT_NAME":"Zuba"}
,{"DOC1":"4737","FILE_NAME":"2345234.PDF","TITLE":"wegwerg","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"4523452","CLIENT_NAME":"Ziba"}
,{"DOC1":"4737","FILE_NAME":"52342345.PDF","TITLE":"egwergw","REPORT_DATE":"30/09/2015 00:00:00","CLIENT_ID":"43532452","CLIENT_NAME":"Ziba"}],"pagination":{"ItemsPerPage":"5","IntervalFrom":"1","IntervalTo":"5","TotalPages":"14","TotalItems":"68","CurrentPage":"1","pageSizes":[{"name":"5","items":5},{"name":"10","items":10},{"name":"25","items":25},{"name":"50","items":50},{"name":"100","items":100}],"maxSize":5}}
[
Appreciate the help....
you pasted a bad-formatted snippet, by the way, you can modify an array using `Array.prototype.map' if you don't need for the memory reference
"use strict";
var data = [{"DOC1":"1234","FILE_NAME":"4321.PDF","TITLE":"gwewrgw","REPORT_DATE":"31/05/2015 00:00:00","CLIENT_ID":"1234512","CLIENT_NAME":"Zuba"}];
var result = data.map(i => {
i.REPORT_DATE = Date.apply(null, i.REPORT_DATE.split(' ').reverse());
return i;
});
console.log(result)

Can a Parse Object be manipulated outside of Cloud Code?

I think Parse has made some changes to its objects without providing a clear memo. I built my app with Node and most of the code rests on my server instead of Cloud Code. Recently I've noticed a number of errors on code that previously tested well. At first I thought it was security settings or Parse versions (I'm currently using the latest version, 1.6.7). I reverted back and updated and nothing has helped with this issue save for transporting my code to the cloud.
I look forward to real help/suggestions, I've already looked at the docs and I'm not finding what I need so please save your breath if you were to suggest that comment. Here is some example code illustrating the problem:
var Parse = require('parse/node');
Parse.initialize("app key", "JS key", "master key");
//for this example the app key and JS key may be backward but they are correct in the project.
var array = [{key: value}, {key1: value1}, {key2: value2}]
var Object = Parse.Object.extend("Table");
var objectQuery = new Parse.Query(Object);
objectQuery.first({
success: function(result){
var Id = result.get("user").id//this correctly provides me with the ID!
_.each(array, function(n){
_.mapObject(n, function(v, k){
var Next = Parse.Object.extend("Info");
var nextQuery = new Parse.Query(Next);
nextQuery.equalTo("name", k);
nextQuery.find({
success: function(Row){
var problem1 = _.map(Row, function(n){return _.find(n)})
console.log(problem1);//this used to show me the JSON
key value pairs if it were an object or the array or
whatever, now I just get ['Info'] from the console.log.
var problem2 = _.map(problem1, function(n){return
_.extend(n, {id: userId})});//this far ['Info']
has proven completely impenetrable. Granted I've used
underscore here but I've tried operations with basic
javascript functions like concat and any data within the
Parse Object is completely ignored. I'd like to do other
stuff from here but there is no point as I can't get
beyond 'undefined' should I try doing anything else with `the data.`
}})})})}})
I'm desperate to move on from this and I believe it is something idiosyncratic. I've scoured Stack Overflow and other sources for days now trying to figure it out. Clearly I need some hand holding and I'm desperate to move on. Thanks.

Having trouble referring to object within array

I am trying to write an html page for class that uses a drop down menu to allow users to pull up a list of relevant information. Unfortunately I am having trouble figuring out how to make the script call on the information in the array. The jsfiddle has the full html section, any help would be GREATLY appreciated.
Please bear in mind that I am not very good with terminology, so be as specific as possible. Especially regarding jQuery, our teacher didn't go over it much so it's a freaking mystery to me.
Also, I do plan on adding more information to the objects in the array, but until I get it working, I don't want to waste the time on something I might need to restructure.
http://jsfiddle.net/GamerGorman20/nw8Ln6ha/11/
var favWebComics = [
Goblins = {1: "www.goblinscomic.org"},
GirlGenious = {1: "www.girlgeniousonline.com"},
GrrlPower = {1: "www.grrlpowercomic.com"}
];
var myFunction = function() {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
document.getElementById("web").innerHTML = favWebComics.x;
};
Again, the JSFiddle link has the full html, there are some unused items currently, but I do plan on adding more of them soon.
My next plan is to incorporate images into the objects, so a picture loads for each selection option. How would I manage that?
[ ] is used for arrays, which are indexed with numbers. If you want named properties, you should use an object, which uses { } for its literals:
var favWebComics = {
Goblins: "www.goblinscomic.org",
GirlGenious: "www.girlgeniousonline.com",
GrrlPower: "www.grrlpowercomic.com"
};
= is for assigning to variables, not specifying property names in an object.
Then you need to understand the difference between . and [] notation for accessing objects. .x means to look for a property literally named x, [x] means to use the value of x as the property name. See Dynamically access object property using variable.
So it should be:
document.getElementById("web").innerHTML = favWebComics[x];
your array is not structured correctly and an object would be better suited:
var favWebComics = {
Goblins : "www.goblinscomic.org",
GirlGenious : "www.girlgeniousonline.com",
GrrlPower : "www.grrlpowercomic.com"
};
then you should be able to access the properties as you intend
favWebComics.Goblins
favWebComics.GirlGenious
favWebComics.GrrlPower
Technically you were treating the array like a dictionary. if you're going to do that but still wanna add more information later you'll need to use brackets {} on the code.
var favWebComics = {
Goblins: ["www.goblinscomic.org"],
GirlGenious: ["www.girlgeniousonline.com"],
GrrlPower: ["www.grrlpowercomic.com"]
};
Also for javascript, as long as your searching key value stores, use braces [] for the call. Here's the working code below.
document.getElementById("web").innerHTML = favWebComics[x];
I have your solution, that displays:
the selected choice
the url
the images
Please check the fiddle.
http://jsfiddle.net/nw8Ln6ha/13/
Your object would be:
var favWebComics = {
Goblins : {url:"www.goblinscomic.org", img:"img1"},
GirlGenious : {url:"www.girlgeniousonline.com", img:"img2"},
GrrlPower : {url:"www.grrlpowercomic.com", img:"img3"}
};
Your display code:
document.getElementById("demo").innerHTML = "You selected: "+x+" "+ eval("favWebComics[\""+x+"\"].url")+" "+ eval("favWebComics[\""+x+"\"].img");

ASP.Net Model to Javascript - Passing Data from server to client

Hey guys quick question what is the best approach on converting Model to Javascript.
I tried using this
#{
var arr = new string[3];
arr[0] = "1";
arr[1] = "2";
arr[2] = "3";
var jason = JsonConvert.SerializeObject(Model);
}
<script type="text/javascript">
var string = '#jason';
var variable2 = jQuery.parseJSON(string);
alert(variable2.Id);
</script>
as you can guess it did not work, I look through the sample of jQuery which should work but I am not sure if it is compatible with JsonConvert of .net
Its my first time on programming in the client side so this is quite a simple question but I tried looking the answer from the net. Mostly I see are uber complicated answers and at least 3 and higher old so I am guessing there should be an easier way to do this now?
I feel like this needs an answer because it's the number 2 result from google and has been viewed over 200 times, and as stated by the OP every other answer is generally long and/or convoluted. But the simplest answer is:
Javascript added to your aspx page:
<script type="text/javascript">
var myObject = <%=JsonConvert.SerializeObject(MyNetObject)%>;
</script>
The key bit being that your output of HTML looks as follows:
<script type="test/javascript">
var myObject = {"Prop1":"value1","Prop2":"Value2"};
</script>
Javascript natively handle JSON so you don't need to reparse anything on the client side. If the object is properly serialized it will be recognized without further conversion (this includes lists and object properties).
In the example provided in the OP the resultant Javascript object would be a simple array. So access to the elements on the client side would be:
alert(variable2[0]), alert(variable2[1]), alert(variable2[2])....
In order to provide the Javascript property calling functionality that OP is trying to do on the client side would require the following on the server side:
var json = JsonConvert.Serialize(new { ID1 = 1, ID2 = 2, ID3 = 3 });
In which an object with Named properties is serialized into the page.

Categories

Resources