Hello my JSON Code looks so:
[
{
name: "Pop",
score: 968
},
{
name: "Rock",
score: 881
},
{
name: "Dance & Electronic",
score: 539
},
And so on...
My problem is that I do not know how to get JSON without JSONObject. I know this question has often been asked. These people do not really help me. Can anyone explain this?
Try This,
try {
JSONArray jsonArray=new JSONArray(jsonStr);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject c = jsonArray.getJSONObject(i);
String name = c.getString("name");
String score = c.getInt("score");
}
} catch (final JSONException e) {
}
That's fine, JSON Array can be extracted without going to JSON object. But for an Android development, it is ideal to use an JSON object with the libraries
Related
I'm a little bit new to programming and very new to JS so I apologize for the beginner question.
I'm trying to iterate through this data and get each tracks name and artist but I'm having an issue. Currently I'm trying something like this.
If anybody has any insight or suggestions I would appreciate it greatly.
I'm using a rails backend with JS frontend. Thank you!
function selectTracks(){
fetch(BACKEND_URL)
.then(response => response.json())
.then(playlist => {
playlist.data.forEach(playlist => {
`<h4> ${playlist.attributes.track.name}</h4>
<h4>${playlist.attributes.track.artist}></h4> `
// let newPlaylist = new Playlist(playlist, playlist.attributes)
console.log(fetch)
// document.getElementById("playlist-container").innerHTML += newPlaylist.renderPlaylistCard();
debugger
}
)}
)
}
My serializer looks like this
{
data: [
{
id: "1",
type: "playlist",
attributes: {
name: "Country Songs",
id: 1,
track_id: 10,
track: {
id: 10,
name: "First Song",
artist: "Randy",
created_at: "2020-06-17T02:09:07.152Z",
updated_at: "2020-06-17T02:09:07.152Z"
}
},
relationships: {
track: {
data: {
id: "10",
type: "track"
}
}
}
}
]
}
You need to replace forEach with map. The 'forEachloop doesn't return anything. But themapmethod return an array. (An array of HTML elements in your case
fetch(BACKEND_URL)
.then(response => response.json())
.then(playlist => {
return playlist.data.map(playlist => {
`<h4> ${playlist.attributes.track.name}</h4>
<h4>${playlist.attributes.track.artist}></h4> `
// let newPlaylist = new Playlist(playlist, playlist.attributes)
console.log(fetch)
// document.getElementById("playlist-container").innerHTML += newPlaylist.renderPlaylistCard();
debugger
}
)}
)
Your code technically works assuming that the BACKEND_URL is correct and the json is valid. But, in its current state, it doesn't do anything with the data. If you output the h4 tags, for instance, you should see them written to the screen.
document.write(
`<h4> ${playlist.attributes.track.name}</h4>
<h4>${playlist.attributes.track.artist}</h4> `
)
Or alternatively you could log the values out to prove that you are processing the data correctly:
console.log(playlist.attributes.track.name, playlist.attributes.track.artist)
If not, the next thing to check is the validity of your json. I'm assuming that you copied your json from the browser which will strip some quotes for readability. View the source to ensure that the key names are correctly wrapped in quotes like this:
{
"data": [
{
"id": "1",
"type": "playlist",
"attributes": {
"name": "Country Songs",
...
If you are using ActiveModel Serializers, they should be formatted correctly.
If your json is valid and you can write the h4 tags to the page with the correct data in them, then the problem probably lies in your Playlist class.
Another handy tool for diagnosing fetch() problems is in Chrome Developer Tools. Go to the Network and click the XHR filter. This will allow you to inspect the fetch request and see if the response is valid and the data is what you expect. Other browsers have a similar feature.
I tried to read sorted data from Cloud Firestore using OrderBy.
And Firestore returned data as Following Order:
AAA
BBB
aaa
bbb
Now, what I want is something like following:
AAA
aaa
BBB
bbb
I want this result only using OrderBy not by manual Sorting.
Is there any way to sort like this in Firestore?
Please provide me a solution for this.
Thanks in Advance.
Sorting and filtering in Cloud Firestore are case sensitive. There is no flag to make the sorting or filtering ignore the case.
The only way to achieve your use-case is to store the field twice.
Let's say your field that stores 'AAA' & 'aaa' is called myData. In your client code you'll need to store a second field called myData_insensitive where you store a case-insensitive copy of the data.
DocA:
-> myData = 'AAA'
-> myData_insensitive = 'AAA'
DocB:
-> myData = 'aaa'
-> myData_insensitive = 'AAA'
DocC:
-> myData = 'BBB'
-> myData_insensitive = 'BBB'
DocD:
-> myData = 'bbb'
-> myData_insensitive = 'BBB'
Now you can query and/or order by myData_insensitive, but display myData.
Two interesting thing about this area is:
With Unicode, removing case is more complex than just 'toLowerCase'
Different human languages will sort the same characters differently
Without creating separate indexes for each collation to solve (2), one implementation approach to deal with (1) is via case folding. If you want to only support modern browser versions, then the following gives you a JavaScript example:
caseFoldNormalize = function (s){
return s.normalize('NFKC').toLowerCase().toUpperCase().toLowerCase()
};
caseFoldDoc = function(doc, field_options) {
// Case fold desired document fields
if (field_options != null) {
for (var field in field_options) {
if (field_options.hasOwnProperty(field)) {
switch(field_options[field]) {
case 'case_fold':
if (doc.hasOwnProperty(field) && Object.prototype.toString.call(doc[field]) === "[object String]") {
doc[field.concat("_insensitive")] = caseFoldNormalize(doc[field])
}
break;
}
}
}
}
return doc;
}
var raw_document = {
name: "Los Angeles",
state: "CA",
country: "USA",
structure: 'Waſſerſchloß',
message: 'quıt quit' // Notice the different i's
};
var field_options = {
name: 'case_fold',
country: 'case_fold',
structure: 'case_fold',
message: 'case_fold'
}
var firestore_document = caseFoldDoc(raw_document, field_options);
db.collection("cities").doc("LA").set(firestore_document).then(function() {
console.log("Document successfully written!");
}).catch(function(error) {
console.error("Error writing document: ", error);
});
This will give you a document in Cloud Firestore with the following fields:
{
"name": "Los Angeles",
"state": "CA",
"country": "USA",
"structure": "Waſſerſchloß",
"message": "quıt quit",
"name_casefold": "los angeles",
"country_casefold": "usa",
"structure_casefold": "wasserschloss",
"message_casefold": "quit quit"
}
To handle older browser, you can see one solution in How do I make toLowerCase() and toUpperCase() consistent across browsers
You could also do it manually after you get your results:
docArray.sort((a, b) => {
if (a.myData.toLowerCase() < b.myData.toLowerCase()) {
return -1;
}
if (a.myData.toLowerCase() > b.myData.toLowerCase()) {
return 1;
}
return 0;
});
It's 2022. Firebase is awesome. Firestore is awesome. You don't need to stop using Firestore because of this limitation. Some things on the noSQL world are made on purpose just to speed up things.
What you can do in cases like this is just to create another property on the document, where you would parse the source value and lowercase it. Then you can use the parsed property to sort/order things.
Example:
interface ICompany {
dateAdded: Date
dateEdited: Date
description: string
id?: string
logo?: string
managers?: ICompanyManager
name: string
nameLowercase: string
website?: string
}
Here if you want to sort companies by name.
What you can do:
query(
companiesCollection,
orderBy('nameLowercase', 'asc'),
)
And when adding/editing:
const company = await addDoc(companiesCollection, {
name: data.name,
nameLowercase: data.name.toLowerCase(),
description: data.description,
website: data.website,
dateAdded: new Date(),
dateEdited: new Date(),
} as ICompany)
Voilà.
I want to initialize a deck of individual cards in Java. This is my approach so far:
public ArrayList<Card> initDeck() {
ArrayList<Card> cardDeck = new ArrayList<Card>(24);
cardDeck.add(new Card("Emperor Augustus", 20.1, 40, 4.1, 300000, POWER_AND_INFLUENCE.VERY_HIGH));
cardDeck.add(new Card("Jeff Bezos", 96, 22, 59.7, 268000, POWER_AND_INFLUENCE.HIGH));
cardDeck.add(new Card("Bill Gates", 83.7, 41, 73, 112388, POWER_AND_INFLUENCE.MEDIUM));
return cardDeck;
}
This is a lot of repetition IMO. Also I want to separate the data from function.
Is it possible to export the elements I want to add into cardDeck, i.e. new Card(...) into a separate file?
In JavaScript you would make it for example like this:
JSON-File:
{
data: [{
name: "asdf",
economy: 123,
yearsInPower: 4
}, {
name: "bsdf",
economy: 3,
yearsInPower: 10
}, {
name: "csdf",
economy: 43,
yearsInPower: 5
}]
}
JS-File:
const cards = require("./cards.json").data;
function initDeck(cards) {
const cardDeck = [];
for (let i = 0; i < cards.length; i++) {
cardDeck.push(cards[i]);
}
return cardDeck;
}
let cardDeck = initDeck(cards);
I've looked into other implementation of the initialization of cards in Java. But all the examples assumes a logical order of the cards, e.g. 2,3,4...Jack, Queen, King, Ace. But in my example the cards don't follow any logical order.
There are several ways that you can separate data from code (like loading from files, database, etc..).
If you wanted to load data from JSON file, then you can use Jackson library to read the data from JSON and convert to Java objects (deserialization) as shown below:
public List<Card> initDeck() throws Exception {
ObjectMapper mapper = new ObjectMapper();
Card[] staff = mapper.readValue(new File("C:\\cards.json"), Card[].class);
List<Card> cardDeck = Arrays.asList(staff);
return cardDeck;
}
Also, as a side note, remember that it is always a best practice to code for interfaces List<Card> as return types (shown above) rather than concrete classes like `ArrayList, you can look here on the same subject.
So in ASP.NET MVC I have a Controller action somewhat like this:
public JsonResult People()
{
var people = db.People.ToList();
return Json(people);
}
and when ajaxed this will return something like this:
[
{
"ID": 1,
"Name": "John Smith"
},
{
"ID": 2,
"Name": "Daryl Jackson"
}
]
However, what I'm looking for is not a JSON array of the records as shown above, but more a JSON object where the IDs of each record is the key and then the record nested as the value, like so:
{
1: {
"Name": "John Smith"
},
2: {
"Name": "Daryl Jackson"
}
}
My initial thought would be to create a Dictionary in C# similar to this structure and pass it into Json() however the method does not know how to handle Dictionary objects.
Is there a way to achieve this kind of structure in C#? Currently I'm having to resort to restructuring it on the client-side or using loops to find a record with the ID I'm searching for. It'd be nicer if I could just get the record by ID in Javascript. Am I going about this all wrong? I'm new to the ASP.NET MVC environment.
Any suggestions would be greatly appreciated. Thank you :)
You can use the ToDictionary() extension method.
public ActionResult People()
{
var peopleDictionary = db.People
.Select(x=> new { Id = x.Id, Name= x.FirstName})
.ToDictionary(d => d.Id.ToString(), p => p);
return Json(peopleDictionary, JsonRequestBehavior.AllowGet);
}
Assuming your People table has an Id and FirstName column, this code will return a json dictionary like this from your table data
{ "101" : {"Id":101,"Name":"John"},"102":{"Id":102,"Name":"Darryl"} }
Using the Json metod, You cannot serialize a dictionary where the dictionary key is of type int, so you need to explicitly convert your int value to a string.
If you want to get a specific user from the a userId, you can use the dictionary style syntax yourJsObject[key]
var url="PutRelativeUrlToReportScoreHere";
$.getJSON(url, function(data) {
console.log(data);
//Get the User with Key 102
console.log(data[102]);
});
I am on a Dojo app, is there any special JS parser which enables me default values within JSON data ?
Example, I'd like to set "maxHeadingLength" in item[1] to the value in item[0].
{
items:[
{
"class": "pmedia.types.PMPlatformRenderConfiguration",
"listItemHeight": "70",
"listItemIconHeight": "60",
"maxDesktopItemsWithBannerP": "9",
"maxDesktopItemsWithBannerL": "9",
"platform": "Default",
"maxHeadingLength":
{
P:300,
L:400
}
},
{
"class": "pmedia.types.PMPlatformRenderConfiguration",
"listItemHeight": "70",
"listItemIconHeight": "60",
"platform": "IPAD",
"maxHeadingLength": "Default"
},
Something like this would good too :
"maxHeadingLength": "this.items[0].maxHeadingLength"
Thanks
Update, It seems I can and need to precise the question a bit better now.
I'd like to write any string expression into the pure JSON string data(file), as string of course and evaluate the data within the same data set without using "eval".
Thanks to all !
You can either do this in a backend process or using a front end process as you process the JSON.
Let's assume you're wanting to do it in the front end using JS, I would suggest firstly setting the items[0].maxHeadingLength as a var, like so:
var defaultMaxHeadingLength = items[0].maxHeadingLength;
And then as you loop through your JSON you can check whether the maxHeadingLength attribute has a value or not and default it, like so:
var item, i;
for ( i = 0; i < items.length; i++ )
{
item = items[ i ];
item.maxHeadingLength = item.maxHeadingLength ? item.maxHeadingLength : defaultMaxHeadingLength;
}
Here's an idea of one way to do it (if I understand what you're trying to do):
var defaultItem = {
"maxHeadingLength": {
P: 300,
L: 400
}
};
var jsondata = {
items: [
{
"class": "pmedia.types.PMPlatformRenderConfiguration",
"listItemHeight": "70",
"listItemIconHeight": "60",
"platform": "IPAD",
"maxHeadingLength": this.defaultItem.maxHeadingLength
}
]
};
alert(jsondata.items[0].maxHeadingLength.L);
//returns 400
Basically you have a default item separate to all your other items, allowing you to refer to the defaults in the main data.
I don't think you can use this.jsondata from within the same object, since it hasn't finished being created yet (but I could be wrong).