Proper way of writing an external JSON file - javascript

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.

Related

Dictionary in javascript that has keys associated with objects [duplicate]

This question already has answers here:
Is it possible to add dynamically named properties to JavaScript object?
(20 answers)
Closed last year.
I need to process a series of data, where each line has the user ID and the data I want to process. I thought a good solution would be to read these files and create a JSON where the keys are the ids and the values are all the data associated with that id.
[
id1 :
{
name: "..."
age: "..."
date_of_birth: "..."
},
id2 :
{
name: "..."
age: "..."
date_of_birth: "..."
},
...
]
However, I'm not sure how I can dynamically add more information to the objects associated with the ID. At each reading of the line of my file, I must look in my dictionary for the ID. If there is already a record of this ID in the dictionary, I should just add a new line in the object associated with it. Otherwise, I must create this key/value pair and add a new line to the object associated with it. Preferably, I would like to build this dictionary in descending order of ids. Any idea how I can build this structure?
if one id can have several instances , it is better to use this structure
{
"id1" : [
{
name: "name1",
age: 1,
date_of_birth: "date1"
}
],
"id2" :[
{
name: "name2",
age: 2,
date_of_birth: "date2"
}
]
}

JSON schema, validate that only one object in array has property equals to value

I have a payload that i want to validate using JSON schema, but there this case that i don't know how to translate to a schema.
Let's say i have this object:
{
jobs: [
{ title: "Developer", salary: "100", actual: false },
{ title: "Plumber", salary: "200", actual: true },
{ title: "Teacher", salary: "100", actual: false }
]
}
i want to write a schema that validates that IF there are objects in the jobs array, one (and only one) of them MUST have the actual key set to true.
Is this possible?
Yes, it's possible. You want to set up a schema with the "items", "contains", "minContains" and "maxContains" keywords that leverage the "if"/"then" ability to write conditionals. That is, in pseudocode:
I have an object with property "jobs", whose value must be an array.
the items in that array are objects, which have properties named "title", "salary" and "actual" (with specific types for each of those values).
either the "jobs" array has zero items, or it must contain exactly one item which has a property named "actual" whose value is a constant of value true.

Groovy/Java regex to separate json names and values in two different arrays

Below sample shows some name and value pair of a json file. In real life I have over 300 name and value pair for the json file where each name is different. SO I thought of getting the names in one array using regex and values in another.
I've reviewed many other questions like this but can't make a head or tail out of them.
what I need is:
I need 2 regular expressions for this piece of JSON.
I want to capture the names with one regex and values with another regex.
The names should include: roleId status seq item1 item2 ... ghost and values should include: 43322 841-1 ... null. NOTICE I left out comma intentionally because I don't want it. Also notice that the last value has no comma.
BTW, I'm using jsonslurper in soapui to parser this json.
I don't if there's any other way I can do it besides regex. Anything will be ok as long as I don't have to type each name to get the value like productDetails[0].roleId which returns 43322. I will have to write over 300 of them.
{
"productDetails": [{
"roleId": 43322,
"status": "",
"seq": "841-1",
"item1": "Yellow",
"item2": "green",
"majorColor": "Black",
"srs": "abc",
"additionalBrightness": null,
"isThisNull": null,
"burned": null,
"ghost": null
}]}
Thanks,

json - look for value and key

I'm quite new to programming and I been googling but couldn't find exactly what I'm looking for.
ok I send a request by ajax and I get response similar to this (the original json is much more complicated)
{
"shelf": {
"genre": {
"title1": {
"date": "date",
"author": "name",
"featured": "N"
}
"title2": {
"date": "date",
"author": "name",
"featured": "Y"
}}}
now I need to do find a "book" which is featured. So I have been looking for a way to look for featured = Y and get it's title in this case "title2".
The best way I could figure out is that when I create the json (in php) when something is featured I can create a new key => value at the same level as "shelf"
"shelf": {
"genre": {
"title1": {
/.../
}
"title2": {
/.../
}}}
"featured": {
"genre": "featuredTitle"
"genre2":"featuredTitle2"
}}}
and then access it in javascript like this:
response.featured['genre'];
and then get all the data by going to
response.shelf.genre.title
but there must be a better way to do it... this gets very messy when the json is very complicated.
Thanks,
Tom
Almost there. You can loop through a JSON object quite easily, JSON is a very friendly format.
var genres = response.shelf.genre;
for (title in genres) {
if (genres.hasOwnProperty(item)) {
var bookTitle = title;
var featured = genres[title].featured;
}
}
The hasOwnProperty is a safety feature you should always use when looping through a JSON object. You can find out more about it here.
More on JSON
JSON solely consists of Javascript Objects and Arrays, one or the other. So even if the stack is complicated, you can always parse it by traversing either an object or an array, and so long as you know the structure of the JSON, it is easy to parse.
// Objects:
myJSON.subObject.anotherSubobject.andAnotherOne;
// Arrays:
myJSON[0]; // accesses first item in array...
myJSON.subObject[2]; // accesses third item in the subObject array.

Create dynamic nested list from JSON using jQuery

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].

Categories

Resources