What is the type of the key in this JSON object {yourVariable: "nothing yet"} - json

Chrome Developer Console is console.loging this:
Your JSON sent is>> {yourVariable: "nothing yet"}
So i know the value "nothing yet" in the {yourVariable: "nothing yet"} JSON object is a string. But how do I know the type of the key yourVariable?
Is there a way how to find that out using the Chrome console only?

All object keys are strings with quotes or without quotes. Try this way to see it. May be you are confused with console print because console print it without quotes and we usually write with quotes.
var jsonObj = {person:"me","age":"30", 123:"123"};
Object.keys(jsonObj).forEach(function(key){
console.log(typeof key)}
);

I have a slightly different take on this question which does not invalidate the comments or answer that you received, but is worth considering.
Because you are talking about JSON, there is no intrinsic datatype in your example. As stated on the JSON.org page:
JSON (JavaScript Object Notation) is a lightweight data-interchange
format. It is easy for humans to read and write. It is easy for
machines to parse and generate.
The point is, that there is a difference between JSON, which is a representation of javascript objects, arrays etc., and variables of those types in javascript.
If you remind yourself that JSON is a form of serialization it makes a lot more sense. Javascript objects for example, can include functions, but a javascript function is not a portable thing, so in rendering some JSON from a javascript object, it is up to the language creating the JSON to do whatever it it needs to in order to convert the data it needs to represent, and that may include simplification and in many cases removal of elements that are incompatible JSON.
The other thing to keep in mind, is that all modern languages have functions or libraries that can parse JSON and turn them into variables or objects that work in those languages. In doing so, they have arguments that can completely change the way the JSON is converted back into instance variables.
For example, in PHP you can choose to have the JSON create one or more PHP objects, or an array of php variables.
In summary, JSON doesn't have variables with datatypes at all. It is a representation of data, that is portable across languages, but the languages must decode the JSON and create objects or variables that are valid in their own runtime.

Related

What's the difference between free-form and non-free-form JSON?

I'm confused what free-form JSON means. Does it mean you can put any types as values in {}?
I thought all JSON are like that (i.e. {'hi':123, 'abc':{'d':[1,2,3],'e':'yay'}}).
So what does free-form JSON mean. Is this a redundant term? Is there such thing as non-free-form JSON?
What you have just posted looks like a JavaScript object, but it is not valid JSON. JSON has some very strict rules, such as all strings must be in double quotes. See JSON.org
There's no such thing as "free-form"/"non-free-form" JSON as every valid JSON-string must be formatted according to the specific rules mentioned on JSON.org.
It's possible that "free-form" JSON is JSON that has been generated "by hand" meaning that you typed it out manually (error prone). Most languages either have built-in methods, or libraries that are available, that turn native data structures (like multi-dimensional arrays) into valid JSON.
PHP, for instance, has a native method called json_encode.

JSON REST endpoint returning / consuming JSON literals

Is it advisable or not in a RESTful web service to use JSON literal values (string / number) as input parameter in the payload or in the response body?
If I have an endpoint PUT /mytodolist is it OK for it to accept a JSON string literal value "Take out the rubbish" in the request payload (with Content-Type=application/json) or should it accept a JSON object instead ({"value":"Take out the rubbish"})?
Similarly, is it fine for GET /mytodolist/1 to return "Take out the rubbish" in the response body or should it return a proper JSON object {"value":"Take out the rubbish"}
Spring MVC to makes implementing and testing such endpoints easy, however clients have flagged this as non standard or hard to implement. In my point of view JSON literals are JSON, but not JSON objects, so I'd say it is fine. I have found no recommendations using Google.
EDIT 1: Clafirication
The question is entirely about the 'standard', if it allows this or not.
I understand the problem with the extensibility, but one can never design a fully extensible interface IMHO. If changes need to be done, we can try extending what we have in a backwards compatible way, but there will come a time when it becomes messy and an other approach is required - which is commonly handled by versioning the API in one way or another. I find it a fair point even though, because using literals as request/response body immediately becomes inextensible, while coming up with a reasonable one-attribute JSON object does not.
It is also understood that some frameworks have problems with handling JSON literals, this is the origin of this question. The tool I used happened to support this, so I thought this was all right, but the front-end library did not.
Still, what I am intending to find out right now, is if using JSON literals is according to the de-facto standard (even if it is a cornercase) or not.
I would recommend to use JSON object always. One reason is that for Content-Type application/json people expect something staring with "{" and not all frameworks will handle json literals properly. Second reason is that probably you will add some additional attributes to you list item (due date, category, priority, etc). And then you'll break backward compatibility, by adding new field.
It may be acceptable in the context of your example, but keep in mind that unambiguous interfaces are easier to use and that will encourage adoption.
For example, your interface could interpret "Take out he rubbish" as the same as {task:"take out the rubbish"}, but once you add additional properties (eg "when" or "who") the meaning of a solitary string in the request becomes ambiguous. It's inevitable that you'll add support for new properties as your interface matures.

Debugging json4s read deserialization errors

I am attempting to consume an API that I do not have control over which is somewhat poorly documentented and somewhat inconsistent. This means that sometimes, the API returns a different type than what is documented or what you would normally see. For this example, we'll look at a case when an array was returned in a place where I would normally see a string. That makes a crappy API, but my real problem is: How can I more easily track those things down? Right now, the errors look something like this:
No usable value for identifier
Do not know how to convert JArray(List(JString(3c8723eceb1a), JString(cba8849e7a2f))) into class java.lang.String
After deciphering the problem (why JValue::toString doesn't emit a JSON string is utterly perplexing to me), I can figure out the API returned an array when I made my case class only able to deal with Strings. Great. My issue is that finding this discrepancy between my object model and the contents of the JSON seems significantly more difficult than it should be.
Currently, this is my workflow for hunting down decoding errors:
Hope bad data has some sort of identifying marker. If this is not true, then it is way more guesswork and you will have to repeat the following steps for each entry that looks like the bad bits.
Go through the troubles of converting the JArray(List(JString(...), ...)) from the error message into valid JSON, hoping that I encode JSON the same way at the API endpoint I got the data from does. If this is not true, then I use a JSON formatter (jq) to format all data consistently.
Locate the place in the source data where the decoding error originates from.
Backtrack through arrays and objects to discover how I need to change my object model to more accurately represent what data is coming back to me from the API.
Some background: I'm coming from C++, where I rolled my own JSON deserialization framework for this purpose. The equivalent error when using the library I built is:
Error decoding value at result.taskInstances[914].subtasks[5].identifier: expected std::string but found array value (["3c8723eceb1a","cba8849e7a2f"]) at 1:4084564
This is my process when using my hand-rolled library:
Look at the expected type (std::string) compared with the data that was actually found (["3c8723eceb1a","cba8849e7a2f"]) and alter my data model for the path for the data in the source (result.taskInstances[914].subtasks[5].identifier)
As you can see, I get to jump immediately to the problem that I actually have.
My question is: Is there a way to more quickly debug inconsistencies between my data model and the results I'm getting back from the API?
I'm using json4s-native_2.10 version 3.2.8.
A simplified example:
{ "property": ["3c8723eceb1a", "cba8849e7a2f"] }
Does not mesh with Scala class:
case class Thing(property: String)
The best solution would be to use Try http://www.scala-lang.org/api/current/#scala.util.Try in Scala, but unfortunately json4s API cannot.
So, I think you should use Scala Option type http://www.scala-lang.org/api/current/#scala.Option .
In Scala, and more generally in functional languages, Options are used to represent an object that can be there or not (like à nil value).
For handle parsing failures, you can use parse(str).toOption, which is a function that return an Option[JValue], and you can doing a pattern matching on the resulting value.
For handling extraction of data extraction into case classes, you can use extractOpt function, to do pattern matching on the value.
You can read this answer : https://stackoverflow.com/a/15944506/2330361

POSTing data to a server with jQuery - why use JSON?

All over the net I see examples of using jQuery to make AJAX POSTs of JSON encoded data to a server. What is the point of encoding the data in JSONfirst? Why not just send it as the default data type application/x-www-url-form-encoded which would save having to parse JSON data on the server?
Couple of reasons. One, it's very easy to turn a JavaScript object into JSON, while it takes effort to encode it as x-www-url-form-encoded. Also, x-www-url-form-encoded isn't really used that much any more. Besides the couple of input types that require a form, most things use AJAX nowadays. Also, JSON is much easier to debug because it's legible.
First, you don't have to use json. If you are more comfortable using any other format, then use it.
But keep in mind, it's all strings. And sometimes it makes sense to use a format like JSON. What happens if you form is dynamic, and you enter multiple instances of the same thing (e.g. name1, name2, name3....)? It's really easy to iterate over such things with JSON. And JSON parsers are readily available for all platforms, so it's not like using it is a hinderance on any platforms. Plus, if both submissions and responses use the same format, there is the benefit of consistency for the data in requests and responses.
JSON is short for JavaScript Object Notation, and is a way to store information in an organized, easy-to-access manner.In a nutshell, it gives us a human-readable collection of data that we can access in a really logical manner.
We use JSON encoding to organize stored information.
Example:
var jason = {
"age" : "24",
"hometown" : "Missoula, MT",
"gender" : "male"
};
To access the information stored in json, we can simply refer to the name of the property we need.
Result:
document.write('Json is ' json.age); // Output: Jason is 24

What is JSON and what is it used for?

I've looked on Wikipedia and Googled it and read the official documentation, but I still haven't got to the point where I really understand what JSON is, and why I'd use it.
I have been building applications using PHP, MySQL and JavaScript / HTML for a while, and if JSON can do something to make my life easier or my code better or my user interface better, then I'd like to know about it. Can someone give me a succinct explanation?
JSON (JavaScript Object Notation) is a lightweight format that is used for data interchanging. It is based on a subset of JavaScript language (the way objects are built in JavaScript). As stated in the MDN, some JavaScript is not JSON, and some JSON is not JavaScript.
An example of where this is used is web services responses. In the 'old' days, web services used XML as their primary data format for transmitting back data, but since JSON appeared (The JSON format is specified in RFC 4627 by Douglas Crockford), it has been the preferred format because it is much more lightweight
You can find a lot more info on the official JSON web site.
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list, or associative array.
An ordered list of values. In most languages, this is realized as an array, vector, list, or sequence.
JSON Structure
Here is an example of JSON data:
{
"firstName": "John",
"lastName": "Smith",
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": 10021
},
"phoneNumbers": [
"212 555-1234",
"646 555-4567"
]
}
JSON in JavaScript
JSON (in Javascript) is a string!
People often assume all Javascript objects are JSON and that JSON is a Javascript object. This is incorrect.
In Javascript var x = {x:y} is not JSON, this is a Javascript object. The two are not the same thing. The JSON equivalent (represented in the Javascript language) would be var x = '{"x":"y"}'. x is an object of type string not an object in its own right. To turn this into a fully fledged Javascript object you must first parse it, var x = JSON.parse('{"x":"y"}');, x is now an object but this is not JSON anymore.
See Javascript object Vs JSON
When working with JSON and JavaScript, you may be tempted to use the eval function to evaluate the result returned in the callback, but this is not suggested since there are two characters (U+2028 & U+2029) valid in JSON but not in JavaScript (read more of this here).
Therefore, one must always try to use Crockford's script that checks for a valid JSON before evaluating it. Link to the script explanation is found here and here is a direct link to the js file. Every major browser nowadays has its own implementation for this.
Example on how to use the JSON parser (with the json from the above code snippet):
//The callback function that will be executed once data is received from the server
var callback = function (result) {
var johnny = JSON.parse(result);
//Now, the variable 'johnny' is an object that contains all of the properties
//from the above code snippet (the json example)
alert(johnny.firstName + ' ' + johnny.lastName); //Will alert 'John Smith'
};
The JSON parser also offers another very useful method, stringify. This method accepts a JavaScript object as a parameter, and outputs back a string with JSON format. This is useful for when you want to send data back to the server:
var anObject = {name: "Andreas", surname : "Grech", age : 20};
var jsonFormat = JSON.stringify(anObject);
//The above method will output this: {"name":"Andreas","surname":"Grech","age":20}
The above two methods (parse and stringify) also take a second parameter, which is a function that will be called for every key and value at every level of the final result, and each value will be replaced by result of your inputted function. (More on this here)
Btw, for all of you out there who think JSON is just for JavaScript, check out this post that explains and confirms otherwise.
References
JSON.org
Wikipedia
Json in 3 minutes (Thanks mson)
Using JSON with Yahoo! Web Services (Thanks gljivar)
JSON to CSV Converter
Alternative JSON to CSV Converter
JSON Lint (JSON validator)
The Concept Explained - No Code or Technical Jargon
What is JSON? – How I explained it to my wifeTM
Me: “It’s basically a way of communicating with someone in writing....but with very specific rules.
Wife: yeah....?
Me: In prosaic English, the rules are pretty loose: just like with cage fighting. Not so with JSON. There are many ways of describing something:
• Example 1: Our family has 4 people: You, me and 2 kids.
• Example 2: Our family: you, me, kid1 and kid2.
• Example 3: Family: [ you, me, kid1, kid2]
• Example 4: we got 4 people in our family: mum, dad, kid1 and kid2.
Wife: Why don’t they just use plain English instead?
Me: They would, but remember we’re dealing with computers. A computer is stupid and is not going to be able to understand sentences. So we gotta be really specific when computers are involved otherwise they get confused. Furthermore, JSON is a fairly efficient way of communicating, so most of the irrelevant stuff is cut out, which is pretty hand. If you wanted to communicate our family, to a computer, one way you could do so is like this:
{
"Family": ["Me", "Wife", "Kid1", "Kid2"]
}
……and that is basically JSON. But remember, you MUST obey the JSON grammar rules. If you break those rules, then a computer simply will not understand (i.e. parse) what you are writing.
Wife: So how do I write in Json?
A good way would be to use a json serialiser - which is a library which does the heavy lifting for you.
Summary
JSON is basically a way of communicating data to someone, with very, very specific rules. Using Key Value Pairs and Arrays. This is the concept explained, at this point it is worth reading the specific rules above.
In short - JSON is a way of serializing in such a way, that it becomes JavaScript code. When executed (with eval or otherwise), this code creates and returns a JavaScript object which contains the data you serialized. This is available because JavaScript allows the following syntax:
var MyArray = [ 1, 2, 3, 4]; // MyArray is now an array with 4 elements
var MyObject = {
'StringProperty' : 'Value',
'IntProperty' : 12,
'ArrayProperty' : [ 1, 2, 3],
'ObjectProperty' : { 'SubObjectProperty': 'SomeValue' }
}; // MyObject is now an object with property values set.
You can use this for several purposes. For one, it's a comfortable way to pass data from your server backend to your JavaScript code. Thus, this is often used in AJAX.
You can also use it as a standalone serialization mechanism, which is simpler and takes up less space than XML. Many libraries exists that allow you to serialize and deserialize objects in JSON for various programming languages.
In short, it is a scripting notation for passing data about. In some ways an alternative to XML, natively supporting basic data types, arrays and associative arrays (name-value pairs, called Objects because that is what they represent).
The syntax is that used in JavaScript and JSON itself stands for "JavaScript Object Notation". However it has become portable and is used in other languages too.
A useful link for detail is here:
http://secretgeek.net/json_3mins.asp
The JSON format is often used for serializing and transmitting structured data over a network connection. It is used primarily to transmit data between a server and web application, serving as an alternative to XML.
JSON is JavaScript Object Notation. It is a much-more compact way of transmitting sets of data across network connections as compared to XML.
I suggest JSON be used in any AJAX-like applications where XML would otherwise be the "recommended" option. The verbosity of XML will add to download time and increased bandwidth consumption ($$$). You can accomplish the same effect with JSON and its mark-up is almost exclusively dedicated to the data itself and not the underlying structure.
the common short answer is: if you are using AJAX to make data requests, you can easily send and return objects as JSON strings. Available extensions for Javascript support toJSON() calls on all javascript types for sending data to the server in an AJAX request. AJAX responses can return objects as JSON strings which can be converted into Javascript objects by a simple eval call, e.g. if the AJAX function someAjaxFunctionCallReturningJson returned
"{ \"FirstName\" : \"Fred\", \"LastName\" : \"Flintstone\" }"
you could write in Javascript
var obj = eval("(" + someAjaxFunctionCallReturningJson().value + ")");
alert(obj.FirstName);
alert(obj.LastName);
JSON can also be used for web service payloads et al, but it is really convenient for AJAX results.
Update (ten years later): Don't do this, use JSON.parse
I like JSON mainly because it's so terse. For web content that can be gzipped, this isn't necessarily a big deal (hence why xhtml is so popular). But there are occasions where this can be beneficial.
For example, for one project I was transmitting information that needed to be serialized and transmitted via XMPP. Since most servers will limit the amount of data you can transmit in a single message, I found it helpful to use JSON over the obvious alternative, XML.
As an added bonus, if you're familiar with Python or Javascript, you already pretty much know JSON and can interpret it without much training at all.
What is JSON?
JavaScript Object Notation (JSON) is a lightweight data-interchange format inspired by the object literals of JavaScript.
JSON values can consist of:
objects (collections of name-value pairs)
arrays (ordered lists of values)
strings (in double quotes)
numbers
true, false, or null
JSON is language independent.
JSON with PHP?
After PHP Version 5.2.0, JSON extension is decodes and encodes functionalities as default.
Json_encode - returns the JSON representation of values
Json_decode - Decodes the JSON String
Json_last_error - Returns the last error occured.
JSON Syntax and Rules?
JSON syntax is derived from JavaScript object notation syntax:
Data is in name/value pairs
Data is separated by commas
Curly braces hold objects
Square brackets hold arrays
Sometimes technicality is given where none is required, and while many of the top voted answers are accurately technical and specific, I personally don't think they are any more easy to understand, or succinct, as what can be found on Wikipedia, or in official documentation.
The way I like to think of JSON is exactly what it is - a language within a world of different languages. However, the difference between JSON and other languages is that "everyone" "speaks" JSON, along with their "native language."
Using a real world example, let's pretend we have three people. One person speaks Igbo as their native tongue. The second person would like to interact with the first person, however, the first person speaks Yoruba as their first language.
What can we do?
Thankfully, the third person in our example grew up speaking English, but also happens to speak both Igbo and Yoruba as second languages, and so can act as an intermediary between the first two individuals.
In the programming world, the first "person" is Python, the second "person" is Ruby, and the third "person" is JSON, who just so happens to be able to "translate" Ruby into Python and vice versa! Now obviously this analogy isn't a perfect one, but, as someone who is bilingual, I believe it's an easy way to look at how JSON interacts with other programming languages.
We have to do a project on college and we faced a very big problem, it is called Same Origin Policy. Amog other things, it makes that your XMLHttpRequest method from Javascript can't make requests to domains other than the domain that your site is on.
For example you can't make request to www.otherexample.com if your site is on www.example.com. JSONRequest allows that, but you will get result in JSON format if that site allows that(for example it has a web service that returns messages in JSON).
That is one problem where you could use JSON perhaps.
Here is something practical: Yahoo JSON
The difference between JSON and conventional syntax would be as follows (in Javascript)
Conventional
function Employee(name, Id, Phone, email){
this.name = name;
this.Id = Id;
this.Phone = Phone;
this.email = email;
}
//access or call it as
var Emp = new Employee("mike","123","9373849784","mike.Anderson#office.com");
With JSON
if we use JSON we can define in different way as
function Employee(args){
this.name = args.name;
this.Id = args.Id;
this.Phone = args.Phone;
this.email = args.email;
}
//now access this as...
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
The important thing we have to remember is that, if we have to build the "Employee" class or modal with 100 elements without JSON method we have to parse everything when creating class. But with JSON we can define the objects inline only when a new object for the class is defined.
so this line below is the way of doing things with JSON(just a simple way to define things)
var Emp = new Employee({'name':'Mike', 'Id':'123', 'Phone':'23792747', 'email':'mike.adnersone#office.com'});
It's very simple. JSON stands for Java Script Object Notation. Think of it as an alternative to using XML for transferring data between software components.
For example, I recently wrote a bunch of web services that returned JSON, and some Javascript developers then wrote code which called the services and consumed the information returned in that format.
JSON(Javascript object notation) is a light weight data format for data exchange/transfer. Its in key value pair as the JavaScript is.
For REST API its widely used for data transfer from server to client. Nowadays many of the social media sites are using this. Although I don't see this as robust as XML with respect of data types. XML has very rich datatypes and XSD. JSON is bit lacking in this.
For same amount of string data JSON will be lighter compare to XML as XML has all that opening and closing tags, etc...
In the Java context, one reason why JSON might want to be used, is that it provides a very good alternative to Java's Serialization framework, which has been shown (historically) to be subject to some fairly serious vulnerabilities.
Joshua Bloch discusses this in depth in Item 85 "Prefer Alternatives to Java Serialization" (Effective Java 3rd Edition)
Java's Serialization was initially meant to translate data structures into a format that could be easily transmitted or stored. JSON meets this requirement, without the serious exploits referred to above.
Try the following code to parse your php json response:
read.php
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$.ajax({
url:'index.php',
data:{},
type:"POST",
success:function(result) {
jsondecoded = $.parseJSON(result);
$.each(jsondecoded, function(index, value) {
$("#servers").text($("#servers").text() + " " + value.servername);
console.log(value.start);
console.log(value.end);
console.log(value.id);
});
},
statusCode: {
404: function() {
alert( "page not found" );
}
}
});
</script>
server.php
<?php
echo '[{"start":"2017-08-29","end":"2017-09-01","id":"22"},{"start":"2017-09-03","end":"2017-09-06","id":"23"}]';
?>