I am building an iOS app in which one of my API calls returns a large JSON blob that I load into a JSON object using SwiftyJSON. For example, it looks something like this
{
"data": {
"name":"object name",
"id":1,
"description":"short description of object",
"type":"type",
"runs":[
],
}
As part of the app the user can modify things like the name, but the API endpoint for the PATCH call needs to have the runs key removed. Does anyone know how to take a SwiftyJSON JSON object and create a new one that has a subset of keys. For example, I want the JSON blob to look like
{
"data": {
"name":"object name",
"id":1,
"description":"short description of object",
"type":"type"
}
I have spent many hours trying various things with no luck. Any help would be greatly appreciated.
You can grab the associated dictionaryValue from your SwiftyJSON object and use the removeValueForKey method.
Of course it means you have to assign the dictionaryValue to a variable, you can't remove a key in the SwiftyJSON object itself.
Example:
var dataDict = json["data"].dictionaryValue
dataDict.removeValueForKey("runs")
Note: the removeValueForKey method name is a bit misleading; it will remove the key, not just the value.
Related
I'm hoping someone can help me. I've been stuck on this for a while now. I am reading a JSON from an API but I have not been successful in converting it and sending it back to my typeahead/autocomplete class. I have attempted several different ways of doing this including JSON Serializable until it wouldn't work and I figured out it won't do nested JSON. The JSON I am reading is not like any of the examples that I have found. I have watched multiple tutorials and read all over stackoverflow. The key value pair I need to read has a key as normal but the value is a list of strings. All of the examples I have found have an object with a key:value pair in the list[]. Can someone please tell me how to read and decode this the easiest way?
Here is an example of the exact JSON:
callback(
{
"status": {
"code": 0
},
"total": 6,
"dictionary_terms": {
"compound": [
"aspirin",
"Aspirine",
"Aspirin sodium",
"Aspirin anhydride",
"Aspirin methyl ester",
"Aspirin calcium"
]
}
}
)
Once you have the object that json.decode(callback) gives, you have a Map<String, dynamic>. So to access compounds in there:
_dynamicMap = json.decode(callback);
List<String> dictionary_terms_compound = _dynamicMap['dictionary_terms']['compound'];
Depending on where you are in null safety, you probably need to either check to make sure each key isn't null. ie, this would fail if dictionary_terms or compound don't exist...so you would need to check for it before you can get the value from it.
So assuming they exist, you might need to put:
List<String> dictionary_terms_compound = _dynamicMap['dictionary_terms']!['compound']!;
The dart definition of your dictionary_terms object is a
Map<String, Map<String,List<String>>>
How can I parse a JSON response from https://api.twitchinsights.net/v1/bots/online to an array in Go and iterate over every entry?
I dont understand the struct because there are no keys only values...
Can anyone please help and explain how this works?
I've mapped it but then I get something like
map[_total:216 bots:[[anotherttvviewer 67063 1.632071051e+09] [defb 26097 1.632071051e+09] [commanderroot 17531 1.632071048e+09] [apparentlyher 16774 1.63207105e+09]...
But I cant iterate over the map.
Because the API you're working with returns data where it could be a string or a number (in the array of arrays property bots), you'll need to use []interface{} as the type for each element of that array because the empty interface (https://tour.golang.org/methods/14) works for any type at run time.
type response struct {
Bots [][]interface{} `json:"bots"`
Total int `json:"_total"`
}
Then, as you iterate through each item in the slice, you can check its type using reflection.
It would be ideal for the API to return data in a schema where every JSON array element has the same JSON type as every other element in its array. This will be easier to parse, especially using statically typed languages like Go.
For example, the API could return data like:
{
"bots": [
{
"stringProp": "value1",
"numberProps": [
1,
2
]
}
],
"_total": 1
}
Then, you could write a struct representing the API response without using the empty interface:
type bot struct {
StringProp string `json:"stringProp"`
NumberProps []float64 `json:"numberProps"`
}
type response struct {
Bots []bot `json:"bots"`
Total int `json:"_total"`
}
But sometimes you're not in control of the API you're working with, so you need to be willing to parse the data from the response in a more dynamic way. If you do have control of the API, you should consider returning the data this way instead.
I'm making API requests to a service which returns a JSON object within the body.
I can't seem to get the value of a key called "properties" within groovy.
Everytime I call obj.properties i get the following back
{
"class": "org.json.JSONObject"
}
but if I call just the obj I get the expected JSON object
{
"dummy1": ,
"dummy2": false,
"dummy3": etsad,
"dummy4": asdfw,
"dummy5": qweqwe,
"dummy6": 123123,
"properties": {
"country": UK,
}
}
Likewise if I obj.dummy2 i get false it's only when I obj.properties do I get the above mentioned response
Notice groovy have a special handling for Object's properties, for example for number:
def y = 25
print y.properties
It will print [class:class java.lang.Integer]
So it's part of basic groovy object
See also an answer about getting non-synthetic properties from groovy object
As #daggett comment, you can use
obj.get('properties')
Check out this answer here on how to access the properties of objects.
The reason obj.properties isn't working is most likely due to the fact that every object will have properties, and in your case obj.properties is getting the properties of the JSON object and not the value associated with the key.
Instead of obj.properties, consider obj['properties']
Is there another way to track what is unmarshalled than write own reverter for each field?
I'm updating my local data based on json message and my problem is (simplified):
I'm expecting json like
{ "items": [ { "id":1, "name":"foobar", "price":"12.34" } ] }
which is then unmarshaled to class TItems by
UnMarshaller.TryCreateObject( TItems, TJsonObject( OneJsonElement ), TargetItem )
My problem is that I can't make difference between
{ "items": [ { "id":1, "name":"", "price":"12.34" } ] }
and
{ "items": [ { "id":1, "price":"12.34" } ] }
In both cases name is blank and i'd like to update only those fields that are passed on json message. Of course I could create a reverted for each field, but there are plenty of fields and messages so it's quite huge.
I tried to look REST.Jsonreflect.pas source, but couldn't make sense.
I'm using delphi 10.
In Rest.Json unit there is a TJson class defined that offers several convenience methods like converting objects to JSON and vice versa. Specifically, it has a class function JsonToObject where you can specify options like for example ignore empty strings or ignore empty arrays. I think the TJson class can serve you. For unmarshalling complex business objects you have to write custom converters though.
Actually, my problem was finally simple to solve.
Instead of using TJSONUnMarshal.tryCreateObject I use now TJSONUnMarshal.CreateObject. First one has object parameters declared with out modifier, but CreateObject has Object parameter var modifier, so I was able to
create object, initalize it from database and pass it to CreateObject which only modifies fields in json message.
I'm developing a server-side RESTful application which serves json data for its client applications. And I have to test so many various json outputs.
Each json has many properties and their validation methods are different like below a sample json.
So such my use-case, do you know good libraries or web services to test json data flexibly?
{
"system": { // data structure validation
"time": 1234566, // data type validation
"version": "0.0.1" // string matching validation
},
"app": { // data structure validation
"id": "1234", // string matching validation
"command": "do something", // string matching validation
"data": { // data structure validation
"hoge": "xxx", // data type validation
"fuga": 123 // data type validation
}
}
}
What do you mean by validating? validating the JSON structure or the data inside your JSON object?
To validate the structure you can parse it to another datatype like dictionary and see if you get any error while.
But to validate the data inside the object you need to validate each object in a very specific way for that object.
Use this link Just Place your JSON code and Test it. Quite easy.