I'm new to GDScript and am looking at how best to save data to a text file. to_json works well for basic types but I just get a reference id for any custom classes. I'd ideally like to pass a dictionary of data including some custom class elements to to_json and let it convert it all at once.
Like other languages provide a toString method for printing an object, is there anything that would let me specify how a class instance should be converted to JSON?
Yeah, you would just add something like the following to your class:
func to_json():
var data = {} #must create it as a dictionary or array
data["health"] = 5
#code to create json
var json
json = data.to_json() #dictionaries automatically have this function
return json
I think it really is that simple :)
Please note: I have not tested this code.
Related
I have this response from an API:
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
how can i select the pix_expiration_date key??? I have tried:
payment_object['acquirer_response']['pix_expiration_date']
it doesnt work and it returns to me:
TypeError: string indices must be integers
Since you’re looking for json
Here’s a code you can start with, keep the good work :)
import json
#importing json
payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'}
###
dic=json.loads(payment_object["acquirer_response"])
#loading the object
dic['pix_expiration_date']
#it will return 2022-04-28T13:46:01.000Z
Are you the owner of the api? If yes:
Edit the response, because it’s sending an string not an object/dictionary
If No:
Convert the string to an dictionary, like if you using python try json library
Your json is not valid. I don't know what language are you using, this code works for javascript, you can easily translate it to another language
var payment_object = {'acquirer_response': '{"object":"transaction", "pix_expiration_date":"2022-04-28T13:46:01.000Z"}'};
var s=JSON.stringify(payment_object).replaceAll("\\","").replaceAll("\"{","{").replaceAll("}\"","}");
var paymentObject=JSON.parse(s);
console.log(paymentObject['acquirer_response']['pix_expiration_date']); // 2022-04-28T13:46:01.000Z
i have this part of my json
POKEAPI get pokemons/sprite/version/
is from POKEAPI, the problem is in kotlin I can't use the '-' for creating a variable, for example: "var myvar-i = 0" and I need to create the variables exactly like the JSON for GSON mapping and the sprites in the JSON I need are like this
generation-i
generation-ii
etc..
in kotlin, I can't create variables with the '-'
enter image description here
someone help me, ¿How can I map that information in kotlin?
You can use the annotation #SerializedName
In your case it would be something like:
class Versions {
#SerializedName("generation-i")
var generation1: Generationgame? = null
...
}
More about the annotation can be found in the docs.
I am newbie in kotlin and I try to copy a JSON structure to another one in an efficient way.
I have an API called getData() how send back a data structure defined as below:
data class DataA(
var id: String,
var cartItems: List<CartItem>,
}
When the getData sent back the DataA structure, I have to map or translate it to another structure defined as below:
data class DataB(
var cartItems: List<CartItem>,
}
Is there an easy way to do it? I know that kotlin can easily encapsulate calls to make it nice.
Thanks
Since you simply need to convert an instance of DataA to an instance of DataB, what you can do is DataB(dataA.cartItems), where dataA is the instance of DataA.
Note, however, that if for any reason you modify any item of cartItems from dataA, this change will be reflected also to dataB, since they share the same list object.
I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]
Any built-in ready-to-use solution in Kendo UI to parse JSON data according to schema.model?
Maybe something like kendo.parseData(json, model), which will return array of objects?
I was searching for something like that and couldn't find anything built-in. However, using Model.set apparently uses each field's parse logic, so I ended up writing this function which works pretty good:
function parse(model, json) {
// I initialize the model with the json data as a quick fix since
// setting the id field doesn't seem to work.
var parsed = new model(json);
var fields = Object.keys(model.fields);
for (var i=0; i<fields.length; i++) {
parsed.set(fields[i], json[fields[i]]);
}
return parsed;
}
Where model is the kendo.data.Model definition (or simply datasource.schema.model), and json is the raw object. Using or modifying it to accept and return arrays shouldn't be too hard, but for my use case I only needed a single object to be parsed at a time.
I actually saw your post the day you posted it but did not have the answer. I just needed to solve this problem myself as part of a refactoring. My solution is for DataSources, not for models directly.
kendo.data.DataSource.prototype.parse = function (data) {
return this.reader.data(data);
// Note that the original data will be modified. If that is not what you want, change to the following commented line
// return this.reader.data($.extend({}, data));
}
// ...
someGrid.dataSource.parse(myData);
If you want to do it directly with a model, you will need to look at the DataReader class in kendo.data.js and use a similar logic. Unfortunately, the DataReader takes a schema instead of a model and the part dealing with the model is not extracted in it's own method.