This question already has answers here:
What is the difference between JSON and Object Literal Notation?
(10 answers)
Closed 7 years ago.
i cant see the difference between:
self.todos = [{
"todo": {
"title": "title",
"content": "lorem"
}
}, {
"todo": {
"title": "title",
"content": "lorem"
}
}];
and
self.todos = [{
todo: {
title: "title",
content: "lorem"
}
}, {
todo: {
title: "title",
content: "lorem"
}
}];
both work in my code but only the first veryfies JSON (online JOSON veryfier). Is there a preference what to use.
thanks a lot
The strict difference between JSON and JavaScript literals is only how you use it.
JSON is a text format to represent data. JavaScript literals is a part of JavaScript code.
You can't use JSON in JavaScript code, because then it's by definition not JSON any more, it's JavaScript. You can take JSON and use as JavaScript code, however. You can also have JSON inside a string in JavaScript.
JSON syntax is a subset of JavaScript literals syntax, so you can take any JSON and use as JavaScript, but you can't take any JavaScript literal and use as JSON.
This is an example of JSON:
[{
"todo": {
"title": "title",
"content": "lorem"
}
}]
You can use that as JavaScript:
var arr = [{
"todo": {
"title": "title",
"content": "lorem"
}
}];
You can also have the JSON as a string and parse it to a JavaScript value:
var json = '[{ "todo": { "title": "title", "content": "lorem" } ]';
var arr = JSON.parse(json);
Note that parsing JSON does't use the JSON as JavaScript, it reads the JSON and creates JavaScript values that corresponds to it. (Before JSON parsing was available the eval function was used to parse JSON, and that would actually use the JSON as JavaScript. JSONP requests still use JSON as JavaScript, as it loads the data using a script tag.)
JavaScript is less strict and doesn't require delimiters for object property names that can be used as identifier. Also, you can use expressions when creating JavaScript literals:
var arr = [{
todo: {
title: document.title,
content: "lo" + "rem"
}
}];
If you take that JavaScript literal and try to use as JSON, the syntax is wrong.
If you're writing JSON, you must conform to the rules for JSON, which include the fact that the property names must be in double quotes. (And that strings must be in double, not single quotes, and there's no undefined or functions, and various other things...)
What you're writing clearly isn't JSON, however, it's JavaScript code; I can tell from the self.todos = part. So you can use no quotes, single quotes, or double quotes on the property names; it's up to you. There are some property names where you need quotes, for instance when the property name has a space:
var o = {
"I have a space": 42
};
The key distinction is that JavaScript source code is source code, and JSON is a textual notation for data exchange which is a simplified version of one small part of JavaScript source code. When you're dealing with JavaScript source code, you're not dealing with JSON, unless you're dealing with strings (e.g., a string containing JSON, which you might parse or send to a server or similar).
Related
I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.
I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.
The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total.
I expect all the elements to be assigned to the variable.
request.open('GET', 'http://localhost:3000/listofvoted', true);
request.onload = function () {
console.log(this.response)
console.log(JSON.parse(this.response));
}
request.send();
The JSON I receive:
{
"name": "Bran",
"name": "Ram",
"name": "Sam"
}
Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.
For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.
Here are some alternative ways of representing what you have that may work:
Use an array of discrete objects:
[
{ "name": "Bran" },
{ "name": "Ram" },
{ "name": "Sam }"
]
Use an array of names:
{
"names": [ "Bran", "Ram", "Sam" ]
}
As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.
See also, How to get the JSON with duplicate keys completely in javascript
I have the following multidimensional javascript array:
My js array
and I want to parse it and return some values from it (name and url)
but when cleaning it up a bit $jsonData = str_replace('var stations = ','' ,$jsonDataUrl); and trying to parse it as json with json_decode($jsongoeshere), the parser returned error 4 even if this URL had told me
that The JSON input is valid in JavaScript.
So now I am a bit lost on how to parse it.
quoted object property name expected is your error.
Your JSON string is not valid, object property names must be quoted.
This
{
"aland": [
{
name: "Ålands Radio",
logo: "stations/images-europe/aland/Ålands Radio.png",
url: "http://194.110.182.131:8000/stream.ogg"
},
...
Should be
{
"aland": [
{
"name": "Ålands Radio",
"logo": "stations/images-europe/aland/Ålands Radio.png",
"url": "http://194.110.182.131:8000/stream.ogg"
},
...
These JSON validators give you the correct error.
https://jsonlint.com/ & https://jsonformatter.curiousconcept.com/
Also, what #JJAulde said is true.
You have a semicolon at the end of your JSON string that will cause the parse to fail. You need to rtrim or str_replace it like you did with var stations =
This question already has answers here:
how to convert json values in comma separated string using javascript
(8 answers)
Closed 5 years ago.
I have a massive JSON file I want to parse into a table column. However, pure JSON is pretty ugly and doesn't really provide much information.
I'd like to reformat it.
Assuming my input it this JSON:
{
"time": "1492511327.863946000",
"type": "Vicious",
"data": {
"subject": "Danger",
"ID": "12314",
"Country": "Russia"
}
}
I wish to output the data object in the following format, and populate it in a single column:
subject=Danger, ID=12314, Country=Russia
(The real object is much much bigger)
I have seen jQuery options to do it, however I do not have access(and will not) to jQuery.
How do I manipulate a large object in JSON format and convert it to the above output, meaning changing the : to = and removing quotation marks.
For the latter part, I could regex myself to replacing them.. If they were strings rather than a big object. But that doesn't really work well in this case.
(Example replace(/['"]+/g, ''))
You can use Object.keys(o) and store this in an array
var obj ={
"time": "1492511327.863946000",
"type": "Vicious",
"data": {
"subject": "Danger",
"ID": "12314",
"Country": "Russia"
}
};
let arr = Object.keys(obj.data).map(k=>`${k}=${obj.data[k]}`);
console.log(arr.join(', '));
I was following this article (https://www.visualstudio.com/docs/integrate/extensions/develop/add-dashboard-widget) to create a widget to add it to microsoft dashboard.
In my html file, there is this piece of code that I cannot get to work:
...(some code above)
return TFS_Wit_WebApi.getClient().getRevision(284,6)
.then(function (query) {
var $list = query.rev;
var $container = $('#query-info-container');
$container.empty();
$container.append($list);
... (some code below)
In this line:
var $list = query.rev;
I'm trying to get access to .json file "rev" variable.
Here is my .json file
{
"count": 15,
"value":
[
{
"id": 284,
"rev": 1,
"fields": {
"System.WorkItemType": "User Story",
"System.State": "New",
"System.Reason": "New",
"System.CreatedDate": "2016-06-23T14:31:37.567Z",
},
...(some code below)
And I'm able to get access to this "rev" variable.
However, now I want to get access to "fields", namely to
"System.State": "New",
Instead of
var $list = query.rev;
I tried
var $list = query.fields.System.WorkItemType[0];
And
var $list = query.value.fields[0];
and
var $list = query.fields;
However, that did not work.
Here is some documentation on how it is supposed to be accessed
fields: {[key: string]: any}.
But it is not much of a help.
Any help will be greatly appreciated!
Thank you!
You can use JSON objects as a kind of "map", what means they are composed of key-value pairs.
var $list = query.fields['System.State'];
There are many different ways of accessing a JSON object properties, as you have already mentioned in your question. However, if the property contains a dot or a space on its name, you need to fall back to the array notation. This means that the following attempts will yeld the correct result:
query.fields
query[fields]
query.fields['System.State']
query[fields]['System.State']
But the ones below will not:
query.fields.System.State
query[fields].System.State
This happens because, in the last two ways, JavaScript will think you are trying to access the State property of the query.fields.System object (which does not exist).
The same applies for objects that have a property whose name contain spaces. Accessing them as object['my property'] will work, but using the dot notation with object.my property will not.
Additional questions regarding this can be seen here:
Dot Notation and Square Bracket Notation in JavaScript
JavaScript property access: dot notation vs. brackets?
What is reason of using ' [ ] ' notation to access javascript object members instead of dot notation?
Try this:
var $list = query.fields["System.WorkItemType"];
JavaScript will interpret the System and WorkItemType as nested properties because of the dot.
Access to json elements is very easy:
1º Create a new var to transform the json data to a new object. Really json has the javascript object format.
var data = '{ "count": 15, "value": [ {"id": 284, "rev": 1, "fields": {"System.WorkItemType": "User Story", "System.State": "New", "System.Reason": "New", "System.CreatedDate": "2016-06-23T14:31:37.567Z", }, ...(some code below) '
var json = JSON.parse(data);
2º Access to a specific element of the object via “.” or “[]”:
Dot notation:
var json.value[n].fields['System.State'];
Note that you can use dot notation with System.State key.
[] notation:
var json['value'][n]['fields']['System.State'];
being n the index to access to a specific element of your object array
This is my JSON object:
{ text: 'stuff',
user: 'user1
}
when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.
So how can I properly access everything in JavaScript?
I don't want to use jQuery as this is all node.js programming so it's serverside.
UPDATED - full JSON
{ text: '#junk_666 おかえりか',
user:
{ display_name: 'mono',
screen_name: 'monochrm',
klout_score: null,
location_str: '画面の前',
utc_offset: '32400' },
venue_id: 1304409836517,
match_type: 'twitter',
tweet_id: '116494264137023489',
created_at_unix: 1316609371,
meta:
{ matchedPhrase: 'junk',
venueName: 'deletemepls really long name' },
tags: [ '' ],
indexed_at_unix: 1316609416 }
The json seems to be invalid
{
"text": "stuff",
"user": "user1"
}
I copied and pasted your object into a FireBug console and it recognized it.
If you need to count the number of key/value pairs, you can use a function such as this one to do it:
function numMembers(o) {
var i=0;
for (a in o) {
i++;
}
return i;
}
You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.
First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.
Secondly, JavaScript objects in general do not have a length property. Arrays do.
There's no problem with your object literal so there must be some other problem elsewhere in your code.
Try this:
{ text: 'stuff',
user: 'user1'
}
You left off an apostrophe.
Now that you've posted your full JS code (that's not JSON, as #josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.