I pass out a ajax get which contains a parameter i.e. date added to db.
Java queries the DB for results of persons added on this date, and builds a JSON object for me like so:
{
"resultdata" : { "rowsReturned" : "2", "fetchTime" : "180"}
"row_1" : { "name" : "Larry", "sex" : "m", "age" : "26", "location" : "seattle" }
"row_2" : { "name" : "Pedro", "sex" : "m", "age" : "22", "location" : "unknown" }
}
I can then return the JSON object as a String. I'd then like to dynamically build a table based on these results.
First of all is the JSON object correct for building a table?
The result data tells me how many rows and the time taken in milliseconds, followed by however many rows in that particular format.
I then want to create a table inside a specific div element once these results are returned to my browser on the fly with no page refreshes etc.
so Id expect Table headers with titles of each column - followed by you guessed it 2 rows.
How is the best way to go about doing this. I am familiar with jQuery, JSON is totally new to me and dealing with JSON in jQuery is something i'm keen on learning.
Any help is much appreciated.
you can use jsonlint to validate your json.
Yours is not valid. It's missing some ',':
{
"resultdata" : {
"rowsReturned" : "2",
"fetchTime" : "180"
}, // <--
"row_1" : {
"name" : "Larry",
"sex" : "m",
"age" : "26",
"location" : "seattle"
}, // <--
"row_2" : {
"name" : "Pedro",
"sex" : "m",
"age" : "22",
"location" : "unknown"
}
}
I've made a little DEMO of one possible way how to loop through the json with for-in-loops
for (key in json) {
loops through the json and stores each key in the 'key' variable.
in your case 'resultdata','row_1','row_2'.
So to access the data for each key you write json[key] which translates to json['row_1'] for example.
Now you do the same thing for the row_1 object with:
for(key1 in json[key])
key1 are now the keys in the row_1 object: 'name','sex',...
to access the data now you'll write json[key][key1] which would be json['row_1']['name'] for example.
of course it's advisable to give the keys meaningful names to avoid confusion like in my example:)
Your JSON looks fine for building a table.
You'll want to use $.getJSON() to fetch the JSON data, as it will automatically parse the JSON into an object for you. If you need the advanced features of $.ajax(), you can call $.parseJSON() on the returned data from the AJAX call and it will parse the JSON into an object.
Related
I am trying to connect to a remote service to receive some JSON data. I would like to model the JSON in an efficient way so that I can deserialise it to a corresponding Java class model.
Say that the JSON I receive is of the format
{
{
"name" : "abc",
"age" : 54,
"gender" : "m",
},
{
"name" : "def",
"age" : 45,
"gender" : "m",
},
{
"name" : "der",
"age" : 43,
"gender" : "f",
},
}
Here are my questions
Is there any way to get the details of a person (say name = "abc") without Iterating over the response ?
If not can you suggest any other JSON format which enables us to quickly access any value
from the response without Iterating.
If Iterating is the only way, then could you also suggest the effective way to model the class and the JSON
The issue in question is as follows:-
I have a POJO with a list of Apple objects , say applesList.
This is stored in Cosmos DB.
When applesList is null, the get endpoint works fine. I get the Pojo as is.
When applesList is populated with apples, i get the error as given in the Title.
How do i fix this?
Json that works with get :-
{
"userId" : "123",
"applesList" : null
}
Json that gives stated error on get, applesList is populated by api :-
{
"userId" : "123",
"applesList" : [
{
"color" : "red",
"weight" : "150 g"
},
{
"color" : "green",
"weight" : "200 g"
}
]
}
Edit :- missed mentioning Cosmos DB SQL API
Change applesList to an array.
I have a content node that I retrieve from a Firebase Realtime Database.
I utilize .orderByChild("time") to get a Data Snapshot of the first 5 blog objects ordered by their earliest timestamps. I
am currently attempting to utilize .indexOn : "time" instead so that I do not have to utilize .orderByChild("time") as I am expecting for the blog objects to already be ordered by their timestamp by back-end when they are retrieved. (I am going to be working with a very large number of blog objects, so I want to utilize .indexOn : "time" in back-end instead of orderByChild("time") in front-end to increase efficiency). Currently, .indexOn does not work and the data isn't ordered by their time fields when it is retrieved.
query without .indexOn
// this works fine
// startAt is utilized for saving last blog object retrieved to retrieve more data
query =
FirebaseDatabase.getInstance().getReference()
.child("content")
.orderByChild("time")
.startAt(nodeId)
.limitToFirst(5);
query with .indexOn
// this along with the Firebase rules below does not return the same result as above
// startAt is utilized for saving last blog object retrieved to retrieve more data
query =
FirebaseDatabase.getInstance().getReference()
.child("content")
.startAt(nodeId)
.limitToFirst(5);
Firebase rules:
{
"rules": {
".read": true,
".write": true,
"content" : {
".indexOn": "time"
}
}
}
JSON structure of data in Firebase :
"content" : {
"blog-0001" : {
"content_id" : "blog-0001",
"image" : "someimage",
"time" : 13,
"title" : "title1",
"type" : "blog"
},
"blog-0002" : {
"content_id" : "blog-0002",
"image" : "someimage",
"time" : 12,
"title" : "title2",
"type" : "blog"
},
"blog-0003" : {
"content_id" : "blog-0003",
"image" : "someimage",
"time" : 11,
"title" : "title3",
"type" : "blog"
},
"blog-0004" : {
"content_id" : "blog-0004",
"image" : "someimage",
"time" : 15,
"title" : "title4",
"type" : "blog"
}
...
}
You seem to be misunderstanding what .indexOn does, and how it related to orderByChild("time").
To retrieve child nodes from content ordered by (and possibly also filtered on) time, you will always need to call orderByChild("time").
If you define an index (using ".indexOn": "time") that ordering and filtering will be done on the server.
Without an index, all data under content will be downloaded to the client, and the ordering/filtering will be performed client side.
So .indexOn is not a replacement for orderByChild. Instead the two work hand in hand to perform efficient ordering and filtering of data.
I need to include some JSON data inside an XML output (I know it might not be the best way, but the system requires it). This problem is part of a Spring REST project. The Java method which generates the XML is annotated as
#RequestMapping(value = "/TEST/pid",
method = RequestMethod.GET, produces = "application/xml")
public String xmlGenerator(String pid){
// definition
}
I could incorporate the JSON data inside the XML output, but the JSON data is not pretty printed. The JSON data is pretty printed before it gets inserted into the XML, but within the XML the JSON is prints out everything in a line. The XML output with JSON data is as follows. Any suggestion how I could pretty print the JSON; the XML is already pretty printed. Appreciate any help. Thanks!
<asec ID="1234-AM0">
<wrap MIMETYPE="application/json" LABEL="JSON DATA">
<xmlData>
<asTest>
{ "pid" : "112233", "pData" : { "type" : "image", "derivatives" : [ { "url" : "//test/url/test1.jpg", "width" : "1538", "height" : "600", "size" : "45168" }, { "url" : "//test/url/test2.jpg", "width" : "64", "height" : "64", "size" : "890" }, { "url" : "//test/url/test3.jpg", "width" : "2888", "height" : "1127", "size" : "180680" } ] } }
</asTest>
</xmlData>
</wrap>
</asec>
--EDIT--
Not sure why someone would mark the question as duplicate. My question is not how to pretty print JSON in Java, I could do that already. My question is how to pretty print the JSON content inside an XML output.
Using Morphia, is it possible to perform a saveOrUpdate / upsert operation on an object embedded inside an array.
Consider the following document :
{
_id : "abcd",
myArray : [{
"key" : "areaTotal",
"value" : "101.9",
"label" : "Total area (municipality)"
}, {
"key" : "areaUrban",
"value" : "803",
"label" : "Total area (urban)"
}, {
"key" : "populationDensity",
"value" : "15991",
"label" : "Population desnsity"
}
]
}
Is there a clean way to replace for example array element with key "areaUrban" by another object
such as
{
"key" : "areaUrban",
"value" : "123",
"label" : "a new label"
}
For now I do it in two update operations first delete, then add :
UpdateOperations<T> ops = createUpdateOperations().removeAll("myArray ", new BasicDBObject("key", "areaUrban"));
update(createQuery().field("_id").equal(myObjId),ops);
UpdateOperations<T> ops2 = createUpdateOperations().add("myArray ", myReplacementObject);
update(createQuery().field("_id").equal(myObjId),ops2);
Which works fine but can I do it in only one update op (either with morphia or with plain mongo java driver) ?
Also if a matching object did not originally exist in the array, then the myReplacementObject object should just be added to the array.
thanks
With the $ positional operator:
db.test.update({_id: "abcd", "myArray.key": "areaUrban"}, {$set: {"myArray.$.value": 123, "myArray.$.label": "a new label"}})
[Edit] As JohnnyHK mentions in the comments this won't upsert the nested document if it doesn't exist.