I have a problem understanding this problem. I have this json in a file called list.json for testing purpose. I will be getting this list generated by server later on.
[
{
name : "ABC",
id : "link_abc"
},
{
name : "DEF",
id : "link_def"
},
{
name : "GHI",
id : "link_ghi"
},
{
name : "JKL",
id : "link_jkl"
}
]
And here's my javascript to display the list in <li> format.
$(function(generate_list_from_JSON){
$('a[href="#state"]').click(function(){
$.getJSON("scripts/list.json", function (obj){
$.each(obj.name, function (key, value){
alert(key);
})
});
});
});
The problem is, there's nothing displayed, even in console. How do I trap what's sending and what's receiving? I tried console.log() but still blank.
JSON requires quotation marks around the attribute names. So you need to do something like this:
[
{
"name" : "ABC",
"id" : "link_abc"
},
...
]
JavaScript objects don't require the attribute names to be quoted, but JSON does.
HTH
I see few problems:
Your JSON object is invalid. It is an array of objects but first two objects are not separated with , and strings in JSON should be quoted.
In your javascript code, you are refering to obj.users, and your object, even if it would have that ,, does not have users at all.
You cannot do an each on obj.name. obj is an array. Arrays do not have a property named "name" and therefore you'll never enter the loop.
Just loop through obj[0] to obj[obj.length-1].
Related
I have object data. in data, we have created the following array:
data = {items: [{ "4","5","6" }, {"7","8","9","10","11","12","13","14","15","16"}]}
console.log("items:", items[0]);
but when use in js I get the error
Unexpected token ','
so can I use that code as an object?
This is not a valid javascript object. Objects in javascript are made up of key-value pairs, which is not the case here. The error is occurring here:
data = {items: [{ "4","5","6" }, {"7","8","9","10","11","12","13","14","15","16"}]}
^
The interpreter is expecting a colon : character whereas you give a comma. You may want to use an array instead.
Furthermore, you need to access the items array via data.items rather than items directly:
data = {items: [[ "4","5","6" ], ["7","8","9","10","11","12","13","14","15","16"]]}
console.log("items:", data.items[0]);
This is a syntax issue. In the list of items you have elements like { "4","5","6" }, but this is not the correct syntax. For a list of items you want to put them between [] symbols; {} symbols are used for objects.
With that in mind, this is probably what you are trying to create:
data = {items: [[ "4","5","6" ], ["7","8","9","10","11","12","13","14","15","16"]]}
I am confused by reading a lot of JSON tutorials on the Internet (even on STO) and not able to decide what is right and what is wrong related to writing an external JSON file.
I have seen so many instances e.g.
(for a single object tho Adobe Dreamweaver CS5.5 shows syntax error, don't know why)
#1
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
}
#2
For multiple objects:
[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
#3
Some have been seen using single quotes around the objects array and storing the array in a variable like this:
customers = '[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]'
#4
A few of them writing above code in the following style:
{
"customers" : [
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
}
#5
One more extra sample format added:
{
[
{
"name" : "Sachin",
"age" : 30,
"country" : "India"
},
{
"name" : "Amit",
"age" : 28,
"country" : "USA"
}
]
}
To be honest, I am totally confused and can't figure out which one is correct and standard style for writing an external .json file (especially those having multiple objects).
So I am asking all my questions here:
What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.
How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?
In which standard format, the third parties APIs present json data?
What is the difference between all above formats? Using single quotes, storing the data in a variable or assigning a key to whole data etc.
You can't use variables in a JSON-file. The third example is probably some snippet of JSON being assigned to a variable within some application.
How should I compose a correct formatted .json file which can easily be read by JavaScript and PHP?
You can start and end the file with square brackets ([ ... ]) if you want to specify an array of multiple objects. If you start and end the file with curly brackets ({ ... }), you specify one top-level object (without a key).
However, you can embed arrays in objects, or include layers of objects. So your last example is indeed valid JSON. Read it as: a top level object, that itself has one attribute 'customers', which contains an array of more objects.
As per its name: JSON = JavaScript Object Notation.
It deals with only 2 things:
Javascript object(s) with any functions stripped out. An object can contain one or more name: value pairs, comma separated. Hopefully you can see that an object is denoted by the presence of { ... }
The JSON definition calls these name/value pairs 'members'. A member name has a colon after the name, so it can be represented as:
{ "name": value }
Value can be any basic javascript type, which are basically object, string, boolean, null OR an array. The safest way to do this so that's maximally interoperable/interchangeable is to always enclose the name in quotes, but it's not strictly necessary to be acceptable json.
So with several properties:
{
"name": "Bob",
"age": 3,
"likes": ["eggs", "ham"],
"parents": [{ "name": "Wilma"}, {"name": "Fred"],
"deleted": false
}
Javascript array
An array is an ordered (ie. 0..n) list of valid json types.
[ 3, "Hello", { "firstname": "Joe", "lastname": "Dimaggio" }, [ 0, 1, 2], true ]
In javascript, you can enclose a string using either single quotes or double quotes, but in json you must always use double quotes.
This won't pass json validation:
{ "name": 'Homer' }
That is all there is to it. An object has a name and a value that could be anything including another object or an array.
Objects are denoted with {} and arrays are denoted with []
Reading a static file is another issue entirely.
With PHP you use json_decode(). That's simple other than whether you want json objects to be turned into php objects, or nested associative arrays where the javascript object property names become the keys of the array. It defaults to making objects, and frequently that's more complicated than an array.
With Javascript often people just want to use the data easily, with the various issues and workarounds illustrated in the linked question.
I am working on a project that has JSON format output. I need a clarity on the JSON array structure. So There are fields that are multiple entry like an array. If an element is an array but has only one value, does it still include an array node '[' in the structure?
Example:
This is a sample JSON element which is an array and has multiple values.
"Talents": [
{
"Items": "test"
},
{
"Items": "test"
}
]
If this element does not have multiple values, will it appear as below?
"Talents":
{
"Items": "test"
}
The '[' does not appear for an array type element with single value. Can someone Pls clarify this?
Single-item arrays will still include the array brackets in JSON format, as they are still arrays. In other words, there is no such native mechanism which converts single-item arrays to a non-array representation. So with your single-item example, it would be represented like this:
"Talents": [
{
"Items": "test"
}
]
You can easily test this out with some simple code:
let jsonSingleItem = { "Talents": [ {"Items": "item1"} ] };
let arraySingleItem = [ {"Items": "item1"} ];
console.log(JSON.stringify(jsonSingleItem));
console.log(jsonSingleItem);
console.log(arraySingleItem);
Which yields the following output:
{"Talents":[{"Items":"item1"}]}
{ Talents: [ { Items: 'item1' } ] }
[ { Items: 'item1' } ]
So in all cases (a stringified JSON object, native JSON, and a javascript array) the single item is still in an array.
Note: It is not uncommon that a consumer of an API will send data (i.e. JSON) in ways which are outside the agreed-upon contract/schema that API defines, and this (sending an object instead of a single-object array when there is just one item) is one example I have seen before. It would be up to the owner/developer of the API as to whether they build in flexibility to handle input which deviates from the API schema.
Square brackets ("[]") denotes JSONArray which in your case can access like
Talents[0]
will return
{
"Items": "test"
}
In second case, curve brackets denotes an JSON object. If you want to access value of items. Than you can by
Talents.Items
OR
Talents["Items"]
will return
"Test"
for complete reference,
JSON Syntax
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.
i have this json returned from my ajax call
[
{message:"haha", type:"error"},
{message:"nice work", type:"success"},
{message:"closed.", type:"success"}
]
and I need to find out if any of the items are of the type error. Now I know I can loop through and figure it out but I wonder if if there is a function that I could tell me what i need to know
You'll have to loop. You can do it with a straightforward loop, or use jQuery.each if you like.
Off-topic: Note that what you've quoted isn't JSON. It's object literal notation. To be valid JSON, the key names would need to be in double quotes:
[
{"message":"haha", "type":"error"},
{"message":"nice work", "type":"success"},
{"message":"closed.", "type":"success"}
]
Some "JSON" parsers (particularly those that are really JavaScript parsers in disguise) are lax and let you get away with it, but that's becoming less common.
Prior to parsing the JSON, you could test the string for a match.
var json = '[{"message":"haha","type":"error"},{"message":"nice work","type":"success"},{"message":"closed.","type":"success"}]'
if( json.indexOf('"type":"error"') > -1 ) {
// there was an error somewhere
}
If the json is a little loose with spaces around the keys/values, you could use a regular expression to test instead.
var json = [
{ "message" : "haha", "type" : "error" },
{ "message" : "nice work", "type" : "success"},
{ "message" : "closed.", "type" : "success"}
];
$.each(json, function(i, k) {
if (k.type === "error") {
// this is an error
// `k.message` contains the expected message
// `i` contains the index key of the array, in this case `0`
}
});
Note: Although my example uses Array and Object literals to express the point (instead of actual JSON text), you should ensure that valid JSON keys are wrapped in quotation marks ¹.
1 for #patrick. :)