What's wrong with my JSON feed? - javascript

I am trying setting up the Fullcalendar JQuery plugin with a JSON feed. It is not working, so I tried with the provided example with the plugin, and it works with that, so it is clearly a problem with my feed.
Here is the output of the example JSON feed (which works):
http://pastebin.com/wFGdhEqu
And here, the output of my JSON feed, which is not working:
http://pastebin.com/UyN4c6yc
Can anyone see anything wrong with the syntax?
The output worked when I printed it inside the .js config with PHP (well, I only changed one things after it wouldnt work: i put quotes on the property names), so I think the data is good...
EDIT: fixed second link

Run your invalid JSON through a validator like JSONLint. It might be quicker than asking people to hand-validate your output.
Updated:
It is easier to work with small sets of data at first than large. You have a couple of problems with your JSON:
Use double quotes, not single quotes
Use a date rather than new Date('xx-xx-xxxx')
Here is a sample of valid JSON using your data:
[
{
"title": "1",
"start": "2011-01-01",
"className": "ottype1"
},
{
"title": "2",
"start": "2011-01-02",
"className": "ottype1"
}
]
If you are creating your JSON by hand (which appears to be the case"), find a library to create your JSON for you.

This is your JSON
, 'start': new Date ('2011-01-01'),
this is the example JSON
,"start":"2011-06-10",
The date formatting is very very very very very very very... buggy.But- the newest version is supposed to be more relaxed.
This is a quote directly from the Documentation.
http://arshaw.com/fullcalendar/docs/event_data/Event_Object/
start Date. Required.
The date/time an event begins.
When specifying Event Objects for
events or eventSources, you may
specify a string in IETF format (ex:
"Wed, 18 Oct 2009 13:00:00 EST"), a
string in ISO8601 format (ex:
"2009-11-05T13:15:30Z") or a UNIX
timestamp.
Notice the 'T' in the time not all serialzers put this 'T' in - so be carefull for that too. And the 'Z' is 'no-time-zoning'; but this can be a pain for people from other countries.. again- also buggy.
And here is a very complex JSON from my site the beggining..
[{"title":"Tee Times","start":"2011-06-30T00:00:00","end":"2011-06-30T00:00:00","allDay":true,"color":"rgb(21,144,51)","groupsize":"","className":"data-brs clickable","cache":null,"EventName":null,"description":null,"EventCompTypeMSP":null,"url":null,"ID":null,"ID2":null,"CompName":null,"CompCourseName":null,"CompNumberDivs":null,"CompQualifierYN":null,"CompNumber":null},{"title":"Test","start":"2011
.. carries on for pages and end
ompetitions.aspx?compID=1088909","ID":40,"ID2":1088909,"CompName":"March Medal","CompCourseName":"Red Tee's","CompNumberDivs":1,"CompQualifierYN":"Y","CompNumber":40}]

Related

Why is date from CSV file being outputted as NaN?

I've just finished a video on Lynda.com and can't get the same results the instructor gets using D3. I've created a simpler version of the files in question, and it still doesn't work. The console outputs NaN when I try to retrieve a date.
The CSV, as output from Excel, is:
Date,AM
1995-04-16,3.5
1995-04-17,14.0
1995-04-18,10.8
and the Javascript file contains:
d3.csv("bg_test_date_parsing.csv", function(d) {
return { Date: +d.Date, AM: +d["AM"] };
}, function(data) {
console.log(data[1]);
});
The console in Mozilla gives me:
Object { Date: NaN, AM: 14 }
I can't proceed with any projects because I don't know where to start with importing dates properly. Videos on lynda.com just keep going, and I still don't get how to import and format dates. Also, the CSV originally was formatted 16-04-1995 as an example, outputted from a medical instrument, and I manually typed it into a year-month-day format that apparently D3 will work with. It took me many hours already using Google to get this far, so I'm obviously missing some key understanding.
+d.Date isn't working the way you want. Calling + on 16-04-1995 is resulting in NaN. You can't convert that string to a number like that.
You can convert the string like this, var myDate = new Date('04-16-1995')
Unfortunately, your format is day-month-year, and javascript wants month-day-year.
See this question for what to do about that:
Convert dd-mm-yyyy string to date
Update As #GerardoFurtado notes in his comment, the d3 library has some built in date parsing options that can convert dates in different formats. See the links in his comment.
Using d3, you could convert the string to a Date like this:
var myDate = d3.timeParse("%d-%m-%Y")('16-04-1995')
or, within your loop:
Date: d3.timeParse("%d-%m-%Y")(d.Date)

converting 'malformed' java json object to javascript

I have a Java JSON Object, its format is [{a=b}], I am trying to pass this object into javascript as a JSON object but its missing " on both the key and value as well as having "=" instead of ":"
Is there a simple way of converting this JAVA JSON object to be consumable by different services?
Parsing is proving to be very complicated as the actual JSON is nested and the lack of quotations and the lacking of indications for nestedness.
Sample of 'JSON' data:
[{wwnType=Virtual, serialNumberType=Virtual, connections=[], modified=2016-10-29T19:00:04.457Z, macType=Virtual, category=server-profile-templates, serverHardwareTypeUri=/rest/server-hardware-types/32006464-D3C6-4B4E-8328-47A193C6116C, bios={overriddenSettings=[], manageBios=false}, firmware={firmwareBaselineUri=null, manageFirmware=false, forceInstallFirmware=false, firmwareInstallType=null}, boot={manageBoot=true, order=[CD, Floppy, USB, HardDisk, PXE]}, hideUnusedFlexNics=true, bootMode=null, state=null, affinity=Bay, localStorage={controllers=[]}, type=ServerProfileTemplateV1, status=OK, description=, eTag=1477767604457/1, serverProfileDescription=test, name=test, created=2016-10-29T19:00:04.428Z, enclosureGroupUri=/rest/enclosure-groups/e989621b-930e-40e7-9db0-a6ddbf841709, uri=/rest/server-profile-templates/db1dbdcc-4237-4452-acc3-cf9dfdc75365, sanStorage={manageSanStorage=false, volumeAttachments=[]}}]
Thanks
It's not going to be simple. However, I think you can do this without writing a full-fledged parser, as long as you're willing to write a tokenizer, or lexical analyzer, to break your input string into tokens. The basic plan could be something like:
Convert your input into a list of tokens. I don't know what the format of your input is, so you'll need to do your own analysis. A token would be something like a single character [, ], {, }, comma, =; or an identifier (a or b in your example, but I don't know what the possible valid formats are); or, maybe, a string literal in quotes, or a numeric literal, depending on what your needs are.
Go through the string and replace the tokens you need to. Based on your example, I'd say that after a {: if the first token after that is an identifier, put it in quotes; if the second token after that is =, change it to :; if the third token after that is an identifier, put it in quotes. The same could be true after a comma, but you'll need to keep track of whether the comma is a separator for a list of key-value pairs in an object, or a list of values in an array. For that, you may need to keep a stack that you push whenever you see [ or {, and pop whenever you see } or ], so that you know whether you're inside an object or an array.
After you're done replacing everything, concatenate the tokens back together. The result should be a well-formed JSON object.
This is just a rough outline, since I really don't know all your requirements. You'll probably have to adapt this answer to meet your exact needs. But I hope this helps as a general idea of how you could approach the problem.
Sorry, I don't think there's a simpler answer, except that you might want to look into parser generators (see Yacc equivalent for Java). I haven't actually looked at any in Java, so I don't know how simple they are to use. Please don't try to solve the whole thing with regexes. (Regexes will be useful for breaking your string into tokens, but trying to do more than that with regexes is likely to produce nothing but migraine.)
I think isn't json object. json object should be like this.
Example:
JSONObject obj = new JSONObject();
obj.put("a", "b");
obj.put("name", "your name");
Output: {"a": "b", "name":"your name"}
Passing into javascript
var obj = '{"a": "b", "name":"your name"}',
var json = JSON.parse(obj);

Parse Javascript To JSON Using Python 3

this is a very specific request, and for that i apologise, but i am at a loss for what to do..
for a javascript project i am working on i want to be able to parse javascript with python and i found this implementation`port of the original narcissus called pynarcissus:
https://github.com/jtolds/pynarcissus
the problem for me is the information is buried in the python class structure.. something with which i am only vaguely competent.. and i want the output to be in JSON
i have tried to mine the data out but each time the JSON is invalid
my question is how would you go about doing something like this? i'd appreciate any specifics because the project contains nested classes of disparate types creating what seems to be a wholly unique problem
here are my attempts:
i took the return value for parse() and created a function that descends through the class structure returning values based on their type: 'str', 'int', 'bool', 'NoneType', 'list', 'dict', 'main.Node', 'main.Tokenizer', 'main.Object'; but the returned object is missing some properties in the classes, ie 'type', while retaining others like 'type_', also tokenizer always contains the same values
i took the output of the str function that the program prints to stdout, removed the clear and copy functions and the tokenizer: [object Object], then tried to manually add in double quotes where necessary to make the output a valid JSON object.. a few problems here, first off ignoring the tokenizer object seems like i am missing out on vital information, and the other problem was that sometimes there is "value" : "{" and sometimes there is "value" : { .. }, after completing the work the JSON was invalid
assuming the issue lied in the "value" : { .. } issue i resolved to add a new function identical the the str function but instead of printing just %s values, it would print \"%s\" where necessary.. now, i could differentiate between "value": "{" and "value" : "{ .. }" but i would have to go through and manually remove the quotes around objects.. after doing so the JSON was invalid
i've tried every copy'pasta solution for python class to json from the stacks but the nested aspect of the classes along with the changing types add complexity.. some properties lack a .dict even when the type is "class 'dict'" so the one'method'fits'all lambda solutions fail
for posterity:
once i massaged the code of pynarcissus to print json i found that the process fails on nested functions.. hilariously exactly the reason i stepped away from my homebrew method
in another thread(i) #firstfire suggested esprima and pyesprima
so i looked into the esprima suggestions, and after a bit of 2to3`ing and some more work returning valid json i got it working and so far it fits my needs perfectly
check out the issue, pull request, and fork:
issues : https://github.com/int3/pyesprima/issues/1
pr : https://github.com/int3/pyesprima/pull/2
fork : https://github.com/ghissues/pyesprima
(i) http://www.linuxquestions.org/questi....php?p=5364199
the old answer::
closed the issue and added a pull request
https://github.com/jtolds/pynarcissus/issues/6
you can check out the fork if you got here by looking for a way to parse javascript to json in python 3
https://github.com/ghissues/pynarcissus

How to get a Date object from json data

I am just trying to parse a Json document with a field Date like this:
´ death':Date('2007-03-17T04:00:00Z') using
com.mongodb.util.JSON.parse(document)
There is an exception when the value Date is encountered. Any help?
The key here is whatever has exported the data has done it wrong. Possibly someone has run something from the MongoDB shell and redirecting console output to a file. That is basically "doing it wrong".
There is a concept called MongoDB Extended JSON and has in fact been picked up in a few other areas, notably the EJSON project.What this tries to do is make sure that any exported JSON maintains "type" information to the BSON type identifier ( or other Object Type, in the purpose of EJSON ) so that a similar "extended JSON" parser can "re-construct" the object to it's intended form.
For a "date" object, the intented JSON representation is this:
{ "death": { "$date": "2007-03-17T04:00:00Z" } }
Since com.mongodb.util.JSON.parse is enabled with knowledge of the Extended JSON spec, then any such JSON contruct will result in a correct date object being constructed from the parsed data.
So what you have right now is just a "string". In fact, if it is not "quoted" like this:
´ { "death" : "Date('2007-03-17T04:00:00Z')" }
Then it is not in fact even valid JSON and would even need to be manipulated to a correct form before even a basic JSON parser would not error. At any rate, the result is just a "string" still, so you would need to make a regex match for the numerical data, then pass that to a date object construct.
Clearly the "best" thing to do here is to fix the "export" source of the data so that it is doing this date parsing to JSON in the correct extended way. Then the parser you are using will do the right thing.

A good way to implement a string tokenizer ( or use one that's already established )

Found myself in a situation where I was making one of two rookie mistakes:
Writing code that I should get out of a library
Writing super complex code that could be greatly simplified using better patterning
What I'm trying to do is pretty simple, I need to send instructions to some JavaScript code that prints fields from an object to the page. Things started out fine, the following string:
message, tags, date
Easily instructed the code to get these elements from the object using
field_array = instruction_string.split(',')
obj['message'], obj['tags'], obj['date']
Then I realized that I wanted to modify that date field to reflect the time zone I was in. Enabling the string to carry special instructions for a field added a little complexity with regex, but still wasn't too complicated:
message, tags, date(GMT-5)
Using the code:
var special_instruction = /\(.*\)/ig.exec('date(GMT-5)')[2]
RESULT: special_instruction = 'GMT-5'
I realized that I was getting in over my head when I realized that I also wanted to tell the output to adjust the date so that it reflects the time delta since right now instead of printing the actual date:
message, tags, date(GMT-5_)(SINCE_NOW)
The regex that I wrote didn't work:
var special_instruction = /\((.*)\)/ig.exec('last_updated(GMT-5)(since_now)')
RESULT: special_instruction = 'GMT-5)(since_now'
Although there is probably a way to fix the regex, this indicates that I should be using a tool or established pattern to do this instead of writing custom code off the cusp and screwing around with it for way too long.
Are you sure you want to use strings and regular expressions for this?
An alternative would be to use an array and objects for defining the fields that should be printed.
Something like this:
var fields = [{
name: 'message'
}, {
name: 'tags'
}, {
name: 'date',
timezone: 'GMT-5',
since: new Date() // now
}];
For getting the values from that sure be printed you can iterate over the array and look for the name field. If you found an object with name date you can look for additional properties. You could also add new properties very easily.

Categories