I've started using Newtonsoft.Json.Schema.JsonSchemaGenerator along with various property attributes over in my C# code to help keep my client script DRY. What I'd like to do is create a default initialized object client-side based on the schema from the server. This would be useful for, say, when the user clicks 'New Foo' to add a new entry into a table.
Obviously I can just code it up to iterate the .Properties and build up the new object, which is what I'm doing at the moment. However I'd prefer to avoid reinventing any wheels.
Are there any JS libraries for working with JSON schema that will do this, among other nifty things I've yet to realize I need?
1/29/2013 UPDATE
Some people have attempted to answer my question and have been off base, and as a result have received some negative feedback from the SO community. So let me attempt to clarify things. Here is the challenge:
In JS client script, you have an object that represents the JSON Schema of another object. Let's say, this came from the server via JSON.NET and is the representation of a C# class.
Now, in the JS client script, create one of these objects based upon the JSON Schema. Each field/property in the object must be default initialized according to the schema, including all contained objects!
BONUS: Bind this new object to the UI using MVVM (eg Knockout). Change some of the fields in response to user input.
Send this new object to the server. The server-side code will add it to a collection, database table, whatever. (Yes, the object will be sent as JSON using Ajax -- we can assume that)
No duplication! The only place where the class is defined is in the server-side code (C# in my example). This includes all metadata such as default values, description text, valid ranges, etc.
Yes there is (I tried it with NodeJS):
JSON Schema defaults
Link updated.
i think...you have to use two way binding with your HTML code...so, once your client side change you will get on your costume js file.
check here for knockout js.
Knock Out JS Link
and on C# code use : $("#urlhidden").val() OR Document.GetElemenyByID("#urlhidden").val().
here you will get array/list or textbox value
Use json with Ko
create new viewmodel for knockout js which you will get the idea about on above link.
and create a json call
like:
self.LoadMAS_Client = function () {
try {
var params = { "clientID": ClientId };
$.ajax({
type: "POST",
url: "http://" + ServerString + "/Services/LogisticsAppSuite-Services-Web-Services-MasClientService.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
// in response u will get the data.and use as per your requirement.
eg. self.SelectedClient(response.your value);
},
error: function (ErrorResponse) {
}
});
}
catch (error) {
}
};
================================New Update ==========================================
i think..one way you can do...get data on xml format at C# code and covert into json string...check below code // To convert an XML node contained in string xml into a JSON string
XmlDocument doc = new XmlDocument();
doc.LoadXml(xml);
string jsonText = JsonConvert.SerializeXmlNode(doc);
// To convert JSON text contained in string json into an XML node
XmlDocument doc = (XmlDocument)JsonConvert.DeserializeXmlNode(json);
Related
So, currently I am passing values stored in Database MySQL to View (using Controller). I do simple querying ModelName::where()->first();.
I have my data right now in View. I want to use that data in Ajax or Javascript code that I am writing.
I can have 46 values and one way to do this is to have <div id="field1"></div> for 46 times set div style to display:none in css and in Javascript use document.getElementById('field1'); to access the values and finally, do whatever I want to do with it.
But I find this quite long and un-necessary to do as there is no point of printing all the values in html first and then accessing it. How can I directly get {{$data}} in Javascript?
myCode
public function index(Request $request){
$cattfs = Cattf::all();
$cattts = Cattt::all();
$cattos = Catto::all();
return view('/index',compact('cattfs'));
}
View
Nothing in the view. and I prefer it to be none.
Javascript and Ajax
$(document).ready(function()
{
init();
});
function init(){
my_Date = new Date();
var feedback = $.ajax({
url:url,
dataType: "JSON",
type: "GET",
}).success(function(data){
console.log(data);
//I have some data called data from url
//I want some data from controller like: cattf,cattt,catto
//I will combine url data and cattf and do simple arithmetic to it
//finally output to the view.
}).responseText;
}
One good way would be to actually make a small API to get your data. Let's say you wanted to retrieve users.
In the api.php file in your route folder:
Route::get('/posts', function () {
return Post::all();
});
and then you just need to use http://yourUrl.dev/api/posts as your URL sent in your .ajax() call to work with what you need.
I found best solution use this: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
It takes values from controller directly to Javascript.
I need to make HTML fill itself with content from JSON file using Mustache or Handlebars.
I created two simple HTML templates for testing (using Handlebars) and filled them with content from an external JavaScript file. http://codepen.io/MaxVelichkin/pen/qNgxpB
Now I need content to lay initially in a JSON file.
I ran into two problems, but they both lie at the heart of solutions of the same main problem - creating a link between the content in the JSON file and HTML, so I decided to ask them in the same question.
How can I connect JSON and HTML? As far as I know there is a way, using AJAX, and there's a way that uses a server. AJAX is a new language for me, so I would be grateful for an explanation of how can I do it, using local HTTP server, that I created using Node.JS.
What should be the syntax in a JSON file? The script in the JSON file must be the same, as a script in JavaScript file, but then it should be processed with the help of JSON.parse function, is that correct? Or syntax in JSON file should be different?
For example, if we consider my example (link above), the code for the first template in the JSON file must be the same as in the JavaScript file, but before the last line document.getElementById('quoteData').innerHTML += quoteData;, I have to write the following line var contentJS = JSON.parse(quoteData);, and then change the name of the variable in the last line, so it will be: document.getElementById('quoteData').innerHTML += contentJS;, Is it right?
Try this:
HTML:
<!-- template-1 -->
<div id="testData"></div>
<script id="date-template" type="text/x-handlebars-template">
Date:<span> <b>{{date}}</b> </span> <br/> Time: <span><b>{{time}}</b></span>
</script>
JS:
function sendGet(callback) {
/* create an AJAX request using XMLHttpRequest*/
var xhr = new XMLHttpRequest();
/*reference json url taken from: http://www.jsontest.com/*/
/* Specify the type of request by using XMLHttpRequest "open",
here 'GET'(argument one) refers to request type
"http://date.jsontest.com/" (argument two) refers to JSON file location*/
xhr.open('GET', "http://date.jsontest.com/");
/*Using onload event handler you can check status of your request*/
xhr.onload = function () {
if (xhr.status === 200) {
callback(JSON.parse(xhr.responseText));
} else {
alert(xhr.statusText);
}
};
/*Using onerror event handler you can check error state, if your request failed to get the data*/
xhr.onerror = function () {
alert("Network Error");
};
/*send the request to server*/
xhr.send();
}
//For template-1
var dateTemplate = document.getElementById("date-template").innerHTML;
var template = Handlebars.compile(dateTemplate);
sendGet(function (response) {
document.getElementById('testData').innerHTML += template(response);
})
JSON:
JSON data format derives from JavaScript, so its more look like JavaScript objects, Douglas Crockford originally specified the JSON format, check here.
JavaScript Object Notation has set of rules.
Starts with open curly braces ( { ) and ends with enclosing curly braces ( } )
ex: {}
Inside baces you can add 'key' and its 'value' like { "title" : "hello json"}
here "title" is key and "hello json" is value of that key.
"key" should be string
"value" can be:
number
string
Boolean
array
object
Can not add JavaScript comments inside JSON (like // or /**/)
there are many online JSON validators, you can check whether your JSON is valid or not, check here.
When comes to linking JSON to js file, its more like provide an interface to get JSON data and use it in your JavaScript.
here XMLHttpRequest our interface. we usually call XMLHttpRequest API.
In the given js code, to get JSON from the server using an REST API (http://date.jsontest.com/)
for more information on REST API you can check here
from the url: http://date.jsontest.com/ you can get JSON object like below.
{
"time": "03:47:36 PM",
"milliseconds_since_epoch": 1471794456318,
"date": "08-21-2016"
}
Note: data is dynamic; values change on each request.
So by using external API you can get JSON, to use it in your JavaScript file/ code base you need to convert JSON to JavaScript object, JSON.parse( /* your JSON object is here */ ) converts JSON to js Object
`var responseObject = JSON.parse(xhr.responseText)`
by using dot(.) or bracket ([]) notation you can access JavaScript Object properties or keys; like below.
console.log(responseObject.time) //"03:47:36 PM"
console.log(responseObject["time"]) //"03:47:36 PM"
console.log(responseObject.milliseconds_since_epoch) //1471794456318
console.log(responseObject["milliseconds_since_epoch"])//1471794456318
console.log(responseObject.date) //"08-21-2016"
console.log(responseObject["date"]) //"08-21-2016"
So to link local JSON file (from your local directory) or an external API in your JavaScript file you can use "XMLHttpRequest".
'sendGet' function updatedin the above js block with comments please check.
In simple way:
create XMLHttpRequest instance
ex: var xhr = new XMLHttpRequest();
open request type
ex: xhr.open('GET', "http://date.jsontest.com/");
send "GET" request to server
ex: xhr.send();
register load event handler to hold JSON object if response has status code 200.
ex: xhr.onload = function () {
for more info check here
Know about these:
Object literal notation
difference between primitive and non-primitive data types
Existing references:
What is JSON and why would I use it?
What are the differences between JSON and JavaScript object?
Basically, JSON is a structured format recently uses which would be preferred due to some advantages via developers, Like simpler and easier structure and etc. Ajax is not a language, It's a technique that you can simply send a request to an API service and update your view partially without reloading the entire page.
So you need to make a server-client architecture. In this case all your server-side responses would be sent in JSON format as RESTful API. Also you can simply use the JSON response without any conversion or something else like an array object in JavaScript.
You can see some examples here to figure out better: JSON example
I'm sending a JS object from my front-end to my Java backend, and I'm passing a object like so, which contains different types
wrapperObject = {
JSONOBJ = {
'key': 'value'
},
id: '123',
date: 'exampledate'
}
My java backend then takes this wrapperObject and converts every field inside into a value inside of a hashmap Map. Whenever it reaches the JSONObject, however, it parses it and attempts to insert into the db and I reach a
bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: No hstore extension installed.
What can I do about this, and is there a better way of approaching this?
It sounds like it may be as simple as adding the hstore extension. The PostgreSQL documentation for installation looks pretty straightforward:
Let me know if I'm missing something, hope this helps!
I'm trying to create a note taking web app that will simply store notes client side using HTML5 local storage. I think JSON is the way to do it but unsure how to go about it.
I have a simple form set up with a Title and textarea. Is there a way I can submit the form and store the details entered with several "notes" then list them back?
I'm new to Javascript and JSON so any help would be appreciated.
there are many ways to use json.
1> u can create a funciton on HTML page and call ajax & post data.
here you have to use $("#txtboxid").val(). get value and post it.
2> use knock out js to bind two way.and call ajax.
here is simple code to call web app. using ajax call.
var params = { "clientID": $("#txtboxid") };
$.ajax({
type: "POST",
url: "http:localhost/Services/LogisticsAppSuite.svc/Json/GetAllLevelSubClients",
contentType: 'application/json',
data: JSON.stringify(params),
dataType: 'json',
async: false,
cache: false,
success: function (response) {
},
error: function (ErrorResponse) {
}
I have written a lib that works just like entity framework. I WILL put it here later, you can follow me there or contact me to get the source code now. Then you can write js code like:
var DemoDbContext = function(){ // define your db
nova.data.DbContext.call(this);
this.notes=new nova.data.Repository(...); // define your table
}
//todo: make DemoDbContext implement nova.data.DbContext
var Notes = function(){
this.id=0; this.name="";
}
//todo: make Note implement nova.data.Entity
How to query data?
var notes = new DemoDbContext().notes.toArray(function(data){});
How to add a note to db?
var db = new DemoDbContext();
db.notes.add(new Note(...));
db.saveChanges(callback);
Depending on the complexity of the information you want to store you may not need JSON.
You can use the setItem() method of localStorage in HTML5 to save a key/value pair on the client-side. You can only store string values with this method but if your notes don't have too complicated a structure, this would probably be the easiest way. Assuming this was some HTML you were using:
<input type="text" id="title"></input>
<textarea id="notes"></textarea>
You could use this simple Javascript code to store the information:
// on trigger (e.g. clicking a save button, or pressing a key)
localStorage.setItem('title', document.getElementById('title').value);
localStorage.setItem('textarea', document.getElementById('notes').value);
You would use localStorage.getItem() to retrieve the values.
Here is a simple JSFiddle I created to show you how the methods work (though not using the exact same code as above; this one relies on a keyup event).
The only reason you might want to use JSON, that I can see, is if you needed a structure with depth to your notes. For example you might want to attach notes with information like the date they were written and put them in a structure like this:
{
'title': {
'text':
'date':
}
'notes': {
'text':
'date':
}
}
That would be JSON. But bear in mind that the localStorage.setItem() method only accepts string values, you would need to turn the object into a string to do that and then convert it back when retrieving it with localStorage.getItem(). The methods JSON.stringify will do the object-to-string transformation and JSON.parse will do the reverse. But as I say this conversion means extra code and is only really worth it if your notes need to be that complicated.
Here's something I want to learn and do. I have a JSON file that contains my product and details (size, color, description). In the website I can't use PHP and MySQL, I can only use Javascript and HTML. Now what I want to happen is using JQuery I can read and write a JSON file (JSON file will serve as my database). I am not sure if it can be done using only JQuery and JSON.
First thing, How to query a JSON file? (Example: I would search for the name and color of the product.)
How to parse the JSON datas that were searched into an HTML?
How to add details, product to the JSON file?
It will also be great if you can point me to a good tutorial about my questions.
I'm new to both JQuery and JSON.
Thanks!
Since Javascript is client side, you won't be able to write to the JSON file on the server using only Javascript. You would need some server side code in order to do that.
Reading and parsing the JSON file is not a problem though. You would use the jQuery.getJSON function. You would supply both a url and a callback parameter (data isn't needed, because you're reading a file, so no need to send data). The url would be the path to your JSON file, and the callback would be a function that uses the data.
Here's an example of what your code might look like. I don't know exactly what your JSON is, but if you have a set called "products" containing a set of objects with the details "name" and "price", this code would print those out:
$.getJSON("getProductJSON.htm",
function(data) {
$.each(data.products, function(i, item) {
var name = item.name;
var price = item.price;
// now display the name and price on the page here!
});
},
);
Basically, the data variable in $.getJSON makes the entire contents of the JSON available to you, very easily. And the $.each is used to loop over a set of JSON objects.