How to decode this json in Firebase realtime Database? - firebase

void readData() {
databaseReference
.child("data")
.child("chapters")
.once()
.then((DataSnapshot snapshot) {
print('Data : ${snapshot.value}');
});
This is my read data function and I got the following JSON output.
[
{
"name": "Global Village",
"videolists": [
{
"title": "Binary to decimal",
"link": "http://..........",
"duration": "5:3"
},
{
"title": "Binary to decimal",
"link": "http://..........",
"duration": "5:3"
}
]
},
{
"name": "Data Communication and Networking",
"videolists": [
{
"title": "Binary to decimal",
"link": "http://..........",
"duration": "5:3"
},
{
"title": "Binary to decimal",
"link": "http://..........",
"duration": "5:3"
}
]
}
]
I have tried to decode the JSON using this code
var lists= json.decode(snapshot.value) as List<dynamic>;
But I got an error like this
Unhandled Exception: type 'List' is not a subtype of type
'String'
How can I decode the JSON?

You can try the following:
Iterable lists = json.decode(result);
List<dynamic> map = lists.toList();
map.forEach((res){
print(res["videolists"][0]);
});
json.decode() takes a String and returns a dynamic, therefore we can assign it to class Iterable and then we can use toList() to create a list and iterate using forEach(). The above should give you:
{title: Binary to decimal, link: http://.........., duration: 5:3}
{title: Binary to decimal, link: http://.........., duration: 5:3}

Related

How to find the parent keys of a jsonpath result

I have this json obj
{
"abc": {
"some_field": {
"title": "Token",
"type": "password"
},
"some_field_2": {
"title": "Domain",
"type": "text"
},
"some_field_3": {
"title": "token2",
"type": "password"
}
}
}
And I want to get a list of keys [some_field,some_field_3] where type=password
This jsonpath $..[?(#.type=='password')] returns:
[
{
"title": "Token",
"type": "password"
},
{
"title": "token2",
"type": "password"
},
]
What should I do?
Thanks.
You are almost there, just need to add a ~ to the end to get the key(s) instead of the value(s):
$..[?(#.type=='password')]~
Note: this might not work depending on your jsonpath engine. It works on https://jsonpath.com.

Logic App > Cosmos PartitionKey Not Matching Error

I'm scared to put this out there because it should be so easy and I am facing the same issue as the post here, here and here and I have tried each of the answers to no avail. Below is the current Resulting Input (redacted) and Related CodeView of the inputs.
The Result
{
"method": "post",
"headers": {
"x-ms-documentdb-raw-partitionkey": "\"2020\""
},
"path": "/dbs/xxxx/colls/smtp/docs",
"host": {
"connection": {
"name": "/subscriptions/..."
}
},
"body": {
"category": [
[
"cat facts"
]
],
"email": "example#test.com",
"event": "processed",
"id": "yada",
"partitionKey": "\"2020\"",
"sg_event_id": "yada yada",
"sg_message_id": "yada",
"smtp-id": "yada",
"timestamp": 1604345542
}
}
The Code View
{
"inputs": {
"body": {
"category": [
"#items('For_each')['category']"
],
"email": "#items('For_each')['email']",
"event": "#items('For_each')['event']",
"id": "#items('For_each')['sg_message_id']",
"partitionKey": "\"#{formatDateTime(utcNow(),'yyyy')}\"",
"sg_event_id": "#items('For_each')['sg_event_id']",
"sg_message_id": "#items('For_each')['sg_message_id']",
"smtp-id": "#items('For_each')['smtp-id']",
"timestamp": "#items('For_each')['timestamp']"
},
"headers": {
"x-ms-documentdb-raw-partitionkey": "\"#{formatDateTime(utcNow(),'yyyy')}\""
}
}
The error I'm getting is the usual one - PartitionKey extracted from document doesn't match the one specified in the header
I just can't see what I'm missing here now.
Thanks all.
First, as Matias comments, check your partition key path.
Then, change this code "partitionKey": "\"#{formatDateTime(utcNow(),'yyyy')}\"", to "partitionKey": "#{formatDateTime(utcNow(),'yyyy')}", in your document.
It works fine on my side:

JSON feed object/array specify root name?

I just discovered and I am very excited about this product... I've had some luck getting my calendar populated... however, I need some more info I cannot explicitly find in the documentation... How do I point to the root JSON object key name "events" if I return an object instead of an array?
If I return an object from SQL like shown here, the events will not be rendered:
{ "events": [ { "id": 434, "title": "Slot 434", "start": "2020-05-20T09:00:00", }, { "id": 435, "title": "Slot 435", "start": "2020-05-20T09:30:00", } ] }
However, if I return an object from SQL like this, they WILL render.
[ { "id": 434, "title": "Slot 434", "start": "2020-05-20T09:00:00", }, { "id": 435, "title": "Slot 435", "start": "2020-05-20T09:30:00", } ]
When using a JSON feed, how to I specify the object root name?
I should mention I am using the events url object:
events: {
url: '[OUR INTERNAL API AND MSSQL SERVER THING]',
method: 'POST',
// extraParams: {
// custom_param1: 'something',
// custom_param2: 'somethingelse'
// },
failure: function () {
alert('there was an error while fetching events!');
},
// color: 'yellow', // a non-ajax option
// textColor: 'black' // a non-ajax option
},

Flutter Firestore, How to add list of objects in array

I need to add list of objects in firestore as shown in the images. i could only add two list with the below code
onPressed: () {
_fireStore.collection('notifyseller').document().updateData({
'Customer': userName,
"address": controller.text,
"mobile": mobileNumber,
"Item": FieldValue.arrayUnion([
{
"name": itemName.toList()[0],
"price": rate.toList()[0],
"quantity": quantity.toList()[0]
},
{
"name": itemName.toList()[1],
"price": rate.toList()[1],
"quantity": quantity.toList()[1]
},
]),
});
},
here itemName.toList() contains list of strings. by the above code i can only add two data. i need to add all the item in the itemName.toList() to that array, instead of giving index for each array
If you are sure that your three list have same length try this;
List yourItemList = [];
for (int i = 0; i < itemName.length; i++)
yourItemList.add({
"name": itemName.toList()[i],
"price": rate.toList()[i],
"quantity": quantity.toList()[i]
});
_fireStore.collection('notifyseller').document().updateData({
'Customer': userName,
"address": controller.text,
"mobile": mobileNumber,
"Item": FieldValue.arrayUnion(yourItemList),
});
i did this way
class Item{
String name;
String price;
String qty;
//named constructor here
Map<String, dynamic> toMap() {
return {
'name': name,
'price': price,
'qty':qty,
};
}
}
List<Items> items = [Item(name:"",price:"",qty:""),Item(name:"",price:"",qty:"")]
_fireStore.collection('notifyseller').document().updateData({
'Customer': userName,
"address": controller.text,
"mobile": mobileNumber,
"Item":, items.map<Map>((e)=> e.toMap()).toList();
});

Decoding Nested JSON Elements (SwiftUI)

I am trying to parse the JSON data below into the structs that are shown. I am having a helluva time trying to figure out how to get at the "nested" elements, such as elements "title:", "content:", and "excerpt:". Whenever the code runs, it barfs while parsing the nested elements.
I've looked at the Apple Developer stuff and reviewed the Playground here: https://developer.apple.com/documentation/foundation/archives_and_serialization/using_json_with_custom_types
I also tried using quicktype.io to create the data models from the sample JSON, however, in the header of the exported file from quicktype it has the line: "let blogItem = try? newJSONDecoder().decode(BlogItem.self, from: jsonData)", however, I get a compile error that jsonData is not recognized and I'm not able to find any reference to it.
struct BlogSection: Codable, Identifiable {
var id: Int
var slug: String
var link: String
var title: [BlogTitle]
var content: [ContentData]
}
struct BlogTitle: Codable, Equatable, Identifiable {
var id: UUID
var rendered: String
}
struct ContentData: Codable, Identifiable{
var id: UUID
var rendered: String
}
/**************** JSON Data ***************/
[
{
"id": 10960,
"date": "2019-10-02T01:00:07",
"date_gmt": "2019-10-02T05:00:07",
"guid": {
"rendered": "example.com/blog-template-copy-copy/"
},
"modified": "2019-09-20T07:08:41",
"modified_gmt": "2019-09-20T11:08:41",
"slug": "relationships-matter",
"status": "publish",
"type": "post",
"link": "example.com/relationships-matter/",
"title": {
"rendered": "Relationships Matter"
},
"content": {
"rendered": "<h1>Page content</h1>",
"protected": false
},
"excerpt": {
"rendered": "<p>By: Joe Schmoe<br />\nFirst Author",
"protected": false
},
"author": 57,
"featured_media": 10958,
"comment_status": "open",
"ping_status": "open",
"sticky": false,
"template": "",
"format": "standard",
"meta": [],
"categories": [
613
],
"tags": [],
"_links": {
"self": [
{
"href": "example.com/wp-json/wp/v2/posts/10960"
}
],
"collection": [
{
"href": "example.com/wp-json/wp/v2/posts"
}
],
"about": [
{
"href": "example.com/wp-json/wp/v2/types/post"
}
],
"author": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/users/57"
}
],
"replies": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/comments?post=10960"
}
],
"version-history": [
{
"count": 5,
"href": "example.com/wp-json/wp/v2/posts/10960/revisions"
}
],
"predecessor-version": [
{
"id": 10971,
"href": "example.com/wp-json/wp/v2/posts/10960/revisions/10971"
}
],
"wp:featuredmedia": [
{
"embeddable": true,
"href": "example.com/wp-json/wp/v2/media/10958"
}
],
"wp:attachment": [
{
"href": "example.com/wp-json/wp/v2/media?parent=10960"
}
],
"wp:term": [
{
"taxonomy": "category",
"embeddable": true,
"href": "example.com/wp-json/wp/v2/categories?post=10960"
},
{
"taxonomy": "post_tag",
"embeddable": true,
"href": "example.com/wp-json/wp/v2/tags?post=10960"
}
],
"curies": [
{
"name": "wp",
"href": "https://api.w.org/{rel}",
"templated": true
}
]
}
}
]
'
In the JSON you do not have arrays for title and content, so just remove the brackets
struct BlogSection: Codable, Identifiable {
var id: Int
var slug: String
var link: String
var title: BlogTitle
var content: ContentData
}
struct BlogTitle: Codable, Equatable, Identifiable {
var id: UUID
var rendered: String
}
struct ContentData: Codable, Identifiable{
var id: UUID
var rendered: String
}
Title and Content are not Arrays in the json provided so should be declared as entities. Your BlogTitle and ContentData are declared as Identifiable and have a variable for id, but both do not have an id in the json provided, so you will get a decoding error because of that as well.
The error you are getting points to a completely different problem though. How is your jsonData declared?

Resources