First, I should point out that I verified my JSON object with http://jsonlint.com and it is, indeed, valid.
Now that is out of the way, I'm looking at examples of the YUI DataTable, specifically the datasource and the structure of the JSON objects the examples use (see http://developer.yahoo.com/yui/examples/datatable/dt_basic.html).
The Basic Example uses a DataSource composed as follows:
YAHOO.example.Data = {
bookorders: [
{id:"po-0167", date:new Date(1980, 2, 24), quantity:1, amount:4, title:"A Book About Nothing"},
{id:"po-0783", date:new Date("January 3, 1983"), quantity:null, amount:12.12345, title:"The Meaning of Life"},
{id:"po-0297", date:new Date(1978, 11, 12), quantity:12, amount:1.25, title:"This Book Was Meant to Be Read Aloud"},
{id:"po-1482", date:new Date("March 11, 1985"), quantity:6, amount:3.5, title:"Read Me Twice"}
]
}
Whereas my JSON object looks like this:
[
{
"Listing": {
"Name": "Jay",
"Address": "Main Street",
"City": "New York"
}
},
{
"Listing": {
"Name": "Thomas",
"Address": "Union Street",
"City": "New York"
}
},
{
"Listing": {
"Name": "Jason",
"Address": "Square Street",
"City": "Boston"
}
}
]
Here is how Yahoo's example specifies the datasource and a few other lines tied to it:
var myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.bookorders);
myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
myDataSource.responseSchema = {
fields: ["id","date","quantity","amount","title"]
};
In my JSON object, each "Listing" would be a row in the YUI DataTable. What do I need to modify in the YUI code to make it work with my JSON object?
Thank you.
Above you have defined an object, with an unnamed array of objects, each object is composed of another object, with members. While this might be valid JSON, I don't think this is compatible with the expectations of the YUI datatable. It is more of a contrived or obfuscated challenge.
I am unable to provide a way, using the existing JSON object. While your JSON is valid, IMHO, I do not believe it to be compatable with the YUI datatable.
I think you need an object containing a named array of objects that have members, not other objects. There are too many layers in the existing data structure, that serve no apparent purpose, to me.
'Change', below, implies changing the basic datatable example, provided by YAHOO.
Simply restructuring your data like so,
YAHOO.example.Data = {
Listing: [
{
"Name": "Jay",
"Address": "Main Street",
"City": "New York"
},
{
"Name": "Thomas",
"Address": "Union Street",
"City": "New York"
},
{
"Name": "Jason",
"Address": "Square Street",
"City": "Boston"
}
]
};
will simplify your data structure and make this work. This is the minimum change, I believe, considering the constraints.
Then change the datasource:
var myDataSource = new YAHOO.util.DataSource(YAHOO.example.Data.Listing);
and the column defs
var myColumnDefs = [
{key:"Name"},
{key:"Address"},
{key:"City"}
];
and finally the response schema
myDataSource.responseSchema = {
fields: ["Name","Address","City"]
};
Hope that helps.
Related
Building a react native app using CosmosDB and it's SQL api.
Per their documentation, I can add an object to a container like this:
const CosmosClient = require('#azure/cosmos').CosmosClient;
const client = new CosmosClient({ endpoint, key });
const myNewObject = {foo: "bar"}
await client
.database(databaseId)
.container(containerId)
.items.create(myNewObject);
And I can confirm this works.
What I'm trying to do tho, is place data into that {foo: "bar"} document that already exists.
So far I've tried chaining the .item method, but it does't work.
await client
.database(databaseId)
.container(containerId)
.item(idOfMyNewObject) // The existing object I want to create a child in
.item('myNewChildObject') // new child of the parent
.create(newEntry); // new entry in the new child
Any ideas? the documentation doesn't seem to talk about this.
There's no method on the container that does this for you. You must define the structure of the data yourself in your code. Here is an example of a customer record which has both an array of addresses as well as an embedded object.
const customer = {
"id": "000242A2-BF40-4220-864B-2770CAA38F5D",
"type": "customer",
"customerId": "000242A2-BF40-4220-864B-2770CAA38F5D",
"title": "",
"firstName": "Timothy",
"lastName": "Kelly",
"emailAddress": "timothy4#adventure-works.com",
"phoneNumber": "193-555-0189",
"creationDate": "2014-03-14T00:00:00",
"addresses": [
{
"addressLine1": "9918 Scottsdale Rd.",
"addressLine2": "",
"city": "Novato",
"state": "CA ",
"country": "US",
"zipCode": "94947",
"location": {
"type": "Point",
"coordinates": [
-122.764,
38.0852
]
}
}
],
"password": {
"hash": "LvEbgjonEPU11HEeSXqdzTsmqNeUfuhxBNL82vGlCWA=",
"salt": "61626BAE"
},
"salesOrderCount": 1
}
Basically, I have a really large JSON file I need to parse, and while searching, I came across this answer.
The only problem is I don't know how to format my JSON array into a single object per line. Is there a straightforward Javascript/Ubuntu way to do this? (I've used jq in the past and it's pretty good for minifying json files, for example)
My JSON file looks something like this
[
{
"country":"monrovia",
"street" :"grove street",
"where" : "home"
},
{
"country": "uk",
"street": "diagon alley",
"where": "mystery"
},
{
...
}
]
But I need it to look like this
[{"country":"monrovia", "street": "grove street", "where": "home" },
{"country": "uk", "street": "diagon alley", "where": "mystery happens"},
{...}]
What you can do is parse the json array by using the JSON.stringify Method like so
// This can be the array of json
var obj = {
"name": "John Doe",
"age": 29,
"location": "Denver Colorado",
};
// stringify the json
var result = JSON.stringify(obj);
// see the output
console.log(result);
jq to the rescue once again! Here is what I needed.
And it's apparently referred to as JSONL.
An even better option is 'new-line delimited JSON' (ndjson). The Javascript implementation of the same (with streams!) is here
I have following JSON data but I don't know how to iterate through it and read its all values:
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
I would like to use following methods to do the needful:
Using for in loop
Using simple for loop
Using $.each in jQuery
I will prefer to display above values in <ul> <li> nicely formatted.
Also, please suggest me what will be look of above JSON data if I put it in an external .json file?
You can use for in loop to iterate over the object, as it iterates over the properties of an object in an arbitrary order, and needs to use .hasOwnProperty, unless inherited properties want to be shown.
Now about accessing the object, let's say I have a JSON like
var myJson={name:"john",age:22,email:"email#domain.com"};
and I need to access the value of name i would simply use . operator using the myJson variable i.e console.log(myJson.name) will output john. because it will be treated as an object, now if I make a little change and make the object like below
var myJson=[{name:"john",age:22,email:"email#domain.com"}];
now if you try to access the value of the property name with the same statement above you will get undefined because the [] will now treat it as an object(JSON) with an array of 1 person or a JSON Array, now if you access it like console.log(myJson[0].name) it will print john in console what if there was more than one person in the array? then it will look like following
var myJson=[
{name:"john",age:22,email:"john#domain.com"},
{name:"nash",age:25,email:"nash#domain.com"}
];
console.log(myJson[0].name) will print john and console.log(myJson[1].name) will print nash so as I mentioned in the start that you should use for in loop for iterating over an object and if we want to print all the names of the person in the JSON Array it will be like.
for(var person in myJson){
console.log(myJson[person].name, myJson[person].age, myJson[person].email);
}
it will output in the console like below
john, 22, john#domain.com
nash, 25, nash#domain.com
I have tried to keep it simple so that you understand you can look into for in and hasOwnProperty, in your case you have a nested object in which property/key subject is an array so if I want to access the first_name of student1 i will write students.student1.first_name and if I want to print the name of the first subject of student1 I will write students.student1.subject[0].name
Below is a sample script to print all the students along with their subjects and marks and personal information since you JSON is nested I am using a nested for in, although Nested iterations are not necessarily a bad thing, even many well-known algorithms rely on them. But you have to be extremely cautious what you execute in the in the nested loops.
For the sake of understanding and keeping the given example of json object, i am using the same to make a snippet. Hope it helps you out
var students = {
"student1": {
"first_name": "John",
"last_name": "Smith",
"age": 24,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
},
"student2": {
"first_name": "David",
"last_name": "Silva",
"age": 22,
"subject": [{
"name": "IT",
"marks": 85
},
{
"name": "Maths",
"marks": 75
},
{
"name": "English",
"marks": 60
}
]
}
};
$("#print").on('click', function() {
for (var student in students) {
console.log(students[student].first_name + '-' + students[student].last_name);
for (var subject in students[student].subject) {
console.log(students[student].subject[subject].name, students[student].subject[subject].marks);
}
}
setTimeout('console.clear()', 5000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" id="print" value="print-now">
If I receive data from a server in plain JSON that looks like this:
{
"f223dc3c-946f-4da3-8e77-e8c1fe4d241b": {
"name": "Dave",
"age": 16,
"jobs": [{
"description": "Sweep the floor",
"difficulty": 4
},{
"description": "Iron the washing",
"difficulty": 6
}]
},
"84af889a-8fc9-499b-a6ea-97e7a483130c": {
...
}
}
Do I need to loop through all the jobs and convert them to Maps, then convert each object's jobs into a List, then the entire thing into a Map?
Or does ImmutableJS do this all recursively for me?
There is Immutable.fromJS() designed for exactly that.
I want to convert the data from an Excel file to a JSON file. However, I'm not sure about the design of my JSON code (i.e. is it organized in a proper way in order to process it easily?)
I will use this JSON file with D3.js.
This a small part of my Excel file:
I'd like to convert this data into a JSON file in order to use it with D3.js. This is what I have so far:
So my question is: is this a good design (way) for organizing the data in order to use it with D3.js?
This is a sample output:
Thanks in advance!
This is a somewhat subjective question, but from my experience, there is a better way:
Since you're working in d3, you're probably doing something like this:
d3.selectAll('div')
.data(entities)
.enter()
.append('div')
...
So you want entities to be an array. The question is what are your entities? Is there a view where entities are all the countries in the world? Is there a view where entities are all the countries plus all the regions plus the whole world? Or, are all the views going to be simply all the countries in a selected region, not including the region itself?
The unless the JSON structure you're proposing matches the combinations of entities that you plan to display, your code will have to do a bunch of concat'ing and/or filtering of arrays in order to get a single entities array that you can bind to. Maybe that's ok, but it will create some unnecessary amount of coupling between your code and the structure of the data.
From my experience, it turns out that the most flexible way (and also probably the simplest in terms of coding) is to keep the hierarchy flat, like it is in the excel file. So, instead of encoding regions into the hierarchy, just have them in a single, flat array like so:
{
"immigration": [
{
"name": "All Countries"
"values: [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Africa"
"values: [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Eastern Africa"
"continent": "Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Burundi"
"continent": "Africa"
"region": "East Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
{
"name": "Djibouti"
"continent": "Africa"
"region": "East Africa"
"values": [
{ "Year": ..., "value": ... },
{ "Year": ..., "value": ... },
...
]
},
...
]
}
Note that even though the array is flat, there is still a hierarchy here -- the region and sub-region properties.
You'll have to do a bit of filtering to extract just the countries/regions you want to show. But that's simpler than traversing the hierarchy you're proposing:
var africanEntities = data.immigration.filter(function(country) {
return country.continent == "Africa";
}); // Includes the region "East Africa"
var justCountries = data.immigration.filter(function(country) {
return country.continent != null && country.region != null;
});
Also, d3 has the awesome d3.nest(), which lets you turn this flat data into hierarchical one with little effort:
var countriesByContinent = d3.nest()
.key(function(d) { return d.continent; })
.map(data.immigration);
var africanEntities = countriesByContinent['Africa'];
Hope that helps....