I have some data stored in JSON format. I would like to be able to display it in a browser as a dynamic tree structure in a similar way MongoVUE presents the mondodb documents:
Screenshot
I have found a very nice jquery plugin, called jsTree. Unfortunately, in order to process JSON documents it requires data to have a very specific verbose (and redundant, in my opinion) structure: link. Using it means significant modifications of my json documents. I am rather searching for a tool that is able to build the tree automagically, without making severe manual adjustments to the data, yet allowing me to potentially apply some modifications to the view, if I would need to.
The tool at json.bloople.net makes something similar using a table, but because I have several levels of nested documents, the output looks very bloated. Moreover, the structure is not dynamically collapsible.
I would appreciate any hints regarding the right tools to do the job, including both those that might require (automated!) pre-processing of JSON data in Java/Groovy or pure JavaScript-based solution.
This is just a simple example of how you could output a tree like JSON structure in html. http://jsfiddle.net/K2ZQQ/1/ (see here for browser support for white-space). Note that the second parameter to JSON.stringify is a replacer function:
From http://msdn.microsoft.com/en-us/library/ie/cc836459(v=vs.94).aspx
If replacer is a function, JSON.stringify calls the function, passing
in the key and value of each member. The return value is used instead
of the original value. If the function returns undefined, the member
is excluded. The key for the root object is an empty string: "".
So if you need to add any further modifications to the dislpay of your JSON tree the replacer function may be of help.
Related
I am using marked.js currently to convert markdown to HTML, so the users of my Web-App can create a structured content. I am wondering if there is a way to restrict the supported syntax tu just an sub-set, like
headers
italic text
bold text
lists with only 1 depth of indentation
quotes
I would like to prohibit conversion of list with multiple levels of indentation, code blocks, headers in lists ...
The reason is, that my WebApp should the users to create content in a specific way and if there will be possibility create some crazy structured content (list of headers, code in headers, lists of images ...) someone will for sure do it.
You have a few difference options:
Marked.js uses a multi-step method to parse Markdown. It uses a lexer, which breaks the document up into tokens, a parser to convert those tokens to a abstract syntax tree (AST) and a renderer to convert the AST to HTML. You can override any of those pieces to alter the handling of various parts of the syntax.
For example, if you simply wanted to ignore lists and leave them out of the rendered HTML, replace the list function from the renderer with one which returns an empty string.
Or, if you want the parser to act as if lists are not even a supported feature of Markdown, you could remove the list and listitem methods from the parser. In that case, the list would remain in the output, but would be treated as a paragraph instead.
Or, if you want to support one level of lists, but not nested lists, then you could replace the list and/or listitem methods in the parser with your own implementation that parses lists as you desire.
Note that there are also a number advanced options, which use the above methods to alter the parser and/or render in various ways. For the most part, those options would not provide the features you are asking for, but browsing though the source code might give you some ideas of how to implement your own modifications.
However, there is the sanitize option, which will accept a sanitizer function. You could provide your own sanitizer which removed any unwanted elements from the HTML output. This would result in a similar end result to overriding the renderer, but would be implemented differently. Depending on what you want to accomplish, one or the other may be more effective.
Another possibility would be to use Commonmark.js, parse the input ant than walk the parsed tree and remove all nodes with/without specific type. See this example, it worked fine for images, but failed for code blocks.
Downside of this approach is, that the parsed markdown source will be traversed two-times: one time for editing and second time for rendering.
I want to compare received JSON data to a JSON 'template', and if it differs in structure (not in data itself) then do something,like discarding that JSON.
Template:
{
"data":{
"id":"1",
"cmd":"34"
}
Succesfull Json:
{
"data":{
"id":"15",
"cmd":"4"
}
Unsuccesfull Json:
{
"data":{
"id":"15"
}
This is only an example, the JSON to evaluate is going to be larger, and I want to avoid checking if each property exists. (This is possible in other languages, hence this question)
It sounds like you're looking for JSON Schema or other similar tools.
JavaScript itself doesn't provide anything built-in to do this for you. So you'll need an already-written tool to do it (such as JSON Schema) or you'll have to do it yourself, checking the existence and (depending on how strict you want to be) type of each property in the received JSON. You can do that either after parsing or during parsing by hooking into the parsing process via a "reviver" function you pass into JSON.parse, but either way is going to require doing the checks. (Given the inside-to-outside way JSON.parse works, I suspect using a reviver for this would be quite hard though. Much better to use a recursive function on the parsed data afterward.)
I would recommend converting it to object JSON.parse(), so you can use javascript API.
If your structure gets more robust in the future (more levels etc), you would be still able to do deep compares. Libraries like Immutable.js will come handy, as it used to compare complex states in React applications.
I recently faced this problem as well. I needed to make some comparisons on some objects (should work for JSON as well). I wrote a package for doing this that might come in handy for people facing this issue in the future (bit late for the topic starter).
https://www.npmjs.com/package/js-object-compare
I have read a lot about parsing JSON with Actionscript. Originally it was said to use this library. http://code.google.com/p/as3corelib/ but it seems Flash Player 11 has native support for it now.
My problem is that I cannot find examples or help that takes you from beginning to end of the process. Everything I have read seems to start in the middle. I have no real experience with JSON so this is a problem. I don't even know how to point ActionScript to the JSON file it needs to read.
I have a project with a tight deadline that requires me to read twitter through JSON. I need to get the three most recent tweets, along with the user who posted it, their twitter name and the time those tweets were posted.
The back end to this is already set up I believe by the development team here, therefor my JSON files or XML just needs to be pointed to and then I need to display the values in the interface text boxes I have already designed and created.
Any help will be greatly appreciated...I do know that there are a lot of threads on here I just do not understand them as they all have some understanding of it to begin with.
You need to:
Load the data, whatever it is.
Parse the data from a particular format.
For this you would normally:
Use URLLoader class to load any data. (Just go to the language reference and look into example of how to use this class).
Use whatever parser to parse the particular format that you need. http://help.adobe.com/en_US/FlashPlatform/beta/reference/actionscript/3/JSON.html this is the reference to JSON API, it also shows usage examples. I'm not aware of these API being in production version of the player, still there might be quite a bit of FP 10.X players out there, so I'd have a fallback JSON parser, but I would recommend using this library: http://www.blooddy.by/en/crypto/ over as3corelib because it is faster. The built-in API are no different from those you would find in browser, so if you look up JSON JavaScript entries, the use should be in general similar to Flash.
After you parse JSON format, you will end up with a number of objects of the following types: Object, Array, Boolean, Number, String. It has also literals to mean null and undefined. Basically, you will be working with native to Flash data structures, you only should take extra care because they will be dynamically constructed, meaning you may not make assumption about existence of parts of the data - you must always check the availability.
wvxvw's answer is good, but I think skips over a to be desired explanation of what JSON itself is. JSON is plain text, javascript object notation, when you read the text on screen it looks something like this
http://www.json.org/example.html
you can see a side by side JSON and XML (both plain text formats) essentially JSON is a bunch of name value pairs.
When you use JSON.parse("your JSON string goes here") it will do the conversions to AS3 "dynamic objects" which are just plain objects (whose properties can be assigned without previously being defined, hence dynamic). But to make a long story short, take the example you see in the link above, copy and paste the JSON as a string variable in AS3, use
var str:String = '{"glossary": {"title": "example glossary","GlossDiv": {"title": "S","GlossList": {"GlossEntry": {"ID": "SGML","SortAs": "SGML","GlossTerm": "Standard Generalized Markup Language","Acronym": "SGML","Abbrev": "ISO 8879:1986","GlossDef": {"para": "A meta-markup language, used to create markup languages such as DocBook.","GlossSeeAlso": ["GML", "XML"]},"GlossSee": "markup"}}}}}';
var test:Object = JSON.parse(str);
method on the string, store it in a variable and use the debugger to see what the resulting object is. As far as I know there's really nothing else to JSON it's simply this format for storing data (you can't use E4X on it since it's not XML based and because of that it's slightly more concise than XML, no closing tags, but in my opionion slightly less readable... but is valid javascript). For a nice break-down of the performance gains/losses between AMF, JSON and XML check out this page: http://www.jamesward.com/census2/ Though many times you don't have a choice with regard to the delivery message format or protocol being used if you're not building the service, it's good to understand what the performance costs of them are.
I would like to be able to store a tree-like structure in a cookie. Ideally, I would like to have something that easily serealizes/deserializes a javascript plain object.
JSON might be a good option, but a quick googling did not filtered out a mainstream approach how to serialize to JSON from JavaScript.
What is the best way to approach the problem?
UPD
Related questions bubbled up Javascript / PHP cookie serialization methods?, which suggests using Prototype's Object.toJSON. I would prefer to stay with jQuery.
UPD2
It turned out that window.JSON.stringify might actually suffice in my case, but mentioned Douglas Crockford's library seems like a good fallback to support browsers where JSON property of the global object is not present.
JSON is your friend.
A free and recognized implementation made by Douglas Crockford is available here
I have used this method to read and store to HTML5's local storage without any problems.
JSON is undoubtedly a good option. To have it work cross-browser include this file in your page https://github.com/douglascrockford/JSON-js/blob/master/json2.js. Then use JSON.stringify() to convert to a string and store, and JSON.parse() to retrieve the object from the cookie.
Be aware that there can be quite low character limits on a single cookie's length, which any jsonified tree could hit, so you might want to preprocess your data before converting to JSON (e.g. replacing booleans with 1's and 0's, switching property names for abbreviated versions) and post-process to reverse these changes after retrieveing from your cookie.
If the amount of data you're storing is really large it may be better to store a session/identifier cookie which is used to retrieve the data from the server via an ajax request (or if you need a quick response on page load, output the data into a script tag) and save the data directly to the server via ajax requests instead of using a cookie.
One more JSON serialization implementation as a jQuery plugin: http://code.google.com/p/jquery-json/
Is there such a thing as JSON namespaces, just like XML namespaces? Has anyone created a spec or libraries for this? Is this a good or a terrible idea?
I want to make a data spec that can be represented in XML as well as JSON. However I also need the namespace concept, that the data can be extended by annotations in different vocabularies.
To be more specific, this is about representing events. My schema will describe the event in basic terms (time and location), though if you think about it, events can be annotated with different information e.g. attendees or image URLs which I don't want to specify in my schema.
JSON-LD might help :
"JSON-LD (JavaScript Object Notation for Linking Data) is a lightweight Linked Data format that gives your data context."
JSON Schema might be the right thing for this:
http://json-schema.org/
Althought I don't know how well it's implemented.
This is quite an old thread, but there are JSON prefixes, which are almost like namespaces. If you are using Java server-side with Jettison, you can easily meet them.