How to add an Element (list) into an JSON. Flutter - arrays

How I get a list/elements in an Json. To get the input i use this:
enterJson(productName, expirydDate, stock, notifications) {
OverviewProduct overviewProduct =
OverviewProduct(productName, expirydDate, stock, notifications);
Map<String, dynamic> map = {
'Product_Name': overviewProduct.productName,
'Expiry_date': overviewProduct.expirydDate,
'Stock': overviewProduct.stock,
'Notifications': overviewProduct.notifications
};
String rawJson = jsonEncode(map);
print(rawJson);
}
Now, i get {"Product_Name":"Test","Expiry_date":"12","Stock":1,"Notifications":true}. This, I would now like to add this into a json file. The json file should have more or less this structure:
[
{
"Product_Name": "Pom-Bär Original",
"Expiry_date" : "10.05.21",
"Stock" : "1",
"Notifications" : "True"
},
{
"Product_Name": "Ja! Natürliches Mineralwasser",
"Expiry_date" : "23.11.21",
"Stock" : "1",
"Notifications" : "True"
}
]

instead of "enterJson" use below code in "OverviewProduct Class":
factory OverviewProduct.fromMap(Map<String, dynamic> map) {
return new OverviewProduct(
Product_Name: map['Product_Name'],
Expiry_date: map['Expiry_date'] ,
Stock: map['Stock'] ,
Notifications: map['Notifications']
);
}
and use it as this:
(map['Products']).map((p) => OverviewProduct.fromMap(p)).toList()

Related

Write an object to an .json file using angular?

I have an object like:
[
{
"text" : "Address of Bowlers game center in Chennai?",
"entities" : [
{
"entity" : "action",
"value" : "business"
},
{
"entity" : "intent",
"value" : "fetchItems"
},
{
"entity" : "bizCategory",
"value" : "bowling",
"start" : 11,
"end" : 30
},
{
"entity" : "wit$location",
"value" : "Chennai",
"start" : 34,
"end" : 40
}
]
},
{
.....more objects
}
]
Now I have to do some manipulation on this object and save the manipulated object into an .json file using angular js.
var originalObject = $http.get("data/chennai.json");
var manipuatedObject; // this is the manipulated object i get after applying some changes on originatalObject.
Now how can I save this manipuatedObject into an json file.
Try this:
function saveText(text, filename){
var a = document.createElement('a');
a.setAttribute('href', 'data:text/plain;charset=utf-u,'+encodeURIComponent(text));
a.setAttribute('download', filename);
a.click()
}
So a possible use might be:
var obj = {a: "Hello", b: "World");
saveText( JSON.stringify(obj), "filename.json" );

Angular Update value in localStorage

The problem I'm having, I can't add/change a given item inside a JSON object. I tried to convert it to use a simple put but that doesn't work since: Property "put" does not exist in type of "JSON"
Key: 123 Value:{"name":"123","email":"123","password":"123","country":"123","about":"123","image":""}
My method to change the country value.
newJson:JSON;
onSubmit(value:any){
this.newJson = JSON.parse(localStorage.getItem(this.id));
this.newJson.put("country", value.country);
localStorage.setItem(JSON.stringify(this.newJson));
}
The value I get from the parameter (the submitted value)
{"country":"Portugal"}
Try like this :
export class Component {
private jsonObj: any = {};
private key: string = "123";
constructor(){
this.jsonObj = {
"name": "123",
"email": "123",
"password": "123",
"country": "123",
"about": "123",
"image": ""
}
localStorage.setItem(this.key, JSON.stringify(this.jsonObj));
}
ngOnInit() {
let localStorageJsonData = JSON.parse(localStorage.getItem(this.key));
localStorageJsonData.country = "france";
localStorage.setItem("obj", JSON.stringify(localStorageJsonData));
console.log('localStorageJsonData', localStorageJsonData);
}
}

Find Firebase Child from Array Values - xcode 8 / swift 3

Id like to get a snapshot with snapshot.key as the UID if the snapshot.value is "pending". Store that into an array. Then i'd like to loop through the array of UID and pull of all the details from .child("users") i.e. "email", "name" & "profileURL". Not sure what the best route is here. Do I store the snapshot into a dictionary then filter dictionary to "pending" or do this within the snapshot call itself?
friends & users JSON structure in my Firebase Database (as below;)
{
"friends" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
},
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : "pending",
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : "pending",
"lNI9FxCErqMUNiW43yiDpkNoljg1" : "pending"
},
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
},
"lNI9FxCErqMUNiW43yiDpkNoljg1" : {
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : "pending"
}
},
"users" : {
"YPQYLtXnMbbmFugrJJPYe6rOIJg2" : {
"email" : "orsrzlqwmt_1488724206#tfbnw.net",
"name" : "Karen Alaedidibgghi Liangescu",
"profileURL" : "someURL"
},
"Z6PnyFKSR9MBMd9dfCEs0VMIOog2" : {
"email" : "rbwimniovp_1488724216#tfbnw.net",
"name" : "Patricia Alaefhcbebjid Warmansen",
"profileURL" : “someURL”
},
"ZyAV7PH4VHWnLyWrWaZty5C9RWT2" : {
"email" : "bhulxppahm_1488724211#tfbnw.net",
"name" : "Harry Alaeejdjagjga Greenestein",
"profileURL" : "someURL"
},
"lNI9FxCErqMUNiW43yiDpkNoljg1" : {
"email" : "axtinlmwes_1488724221#tfbnw.net",
"name" : "Maria Alaefehgadbdg Valtchanovsky",
"profileURL" : "someURL"
}
}
}
Any help greatly appreciated. Cheers!
Here's how you'd get started, once you have your parsed data you can use different methods to filter it which you can look up through different stackoverflow questions answered in the past.
let dbRef = FIRDatabase.database().reference.child("friends")
dbRef.observeSingleEvent(of: .value, with: { snapshot in
if let data = snapshot.value as? [String: [String: String]] {
for user in data {
// You'll now have a dictionary with neatly formatted values you can filter
}
}
})

Join queries in meteor angular using publish composite

I have two Collections Category and Feeds.
Category
{
"_id": "ADFGFDF",
"title" : "title",
}
Feeds
{
"_id": "DFSAHT",
"feeds" : "ds sdsd sds",
"categoryId" : "catId"
}
I need to get the result like this:
{
"_id": "ADFGFDF",
"title" : "title",
"categoryId" : "DFSAHT"
"category" : {
"_id": "DFSAHT",
"feeds" : "ds sdsd sds",
}
}
I tried using publish-composite and here it's my code.
Server
Meteor.publishComposite('feedscateg', function () {
return {
find: function () {
return Category.find({});
},
children: [
{
find: function (cat) {
return Feeds.find({ categoryID: cat._id });
}
}
]
}
});
In client Angular i tried this:
$scope.feeds = $meteor.collection(Category).subscribe('feedscateg');
And I am confused with the view part also.
publishComposite do not modify collection data, it will load Feeds and Category separately. If you want to get category of feed item just select it from client db.
$scope.getFeedCategory = function (feedItem) {
Category.findOne({'_id': feedItem.categoryId});
};

$push in MongoDb not working?

my schema looks like this:
var exampleSchema = newSchema({
profile:{
experience :[{
exp : String
}]
}
});
this is the codes to update experience in profile collection:
exampleSchema.statics.experience = function (id,experience, callback){
var update = {
$push: {
'profile.experience': experience
}
}
this.findByIdAndUpdate(id,update,function(err) {
if (err) {
callback(err);
} else {
callback(null);
}
})
I was getting error like The field 'profile.experience' must be an array but is of type String in document {_id: ObjectId('5653f1d852cf7b4c0bfeb54a')}[object Object]
console.log(experience) is equal to
{ exp: 'jlkjlkjlk' }
my collection should look like this:
experience:[
{
exp : "YYYY"
},
{
exp:"xxxx"}
]
Imagine that you have this collection:
/* 1 */
{
"_id" : ObjectId("565425e862760dfe14339ba8"),
"profile" : {
"experience" : [
{
"exp" : "Experto"
}
]
}
}
/* 2 */
{
"_id" : ObjectId("565425f562760dfe14339ba9"),
"profile" : {
"experience" : {
"exp" : "Experto"
}
}
}
/* 3 */
{
"_id" : ObjectId("5654260662760dfe14339baa"),
"profile" : {
"experience" : "Experto"
}
}
If you try (update doc /* 2 */):
db.profile.update(
{ _id: ObjectId("565425f562760dfe14339ba9") },
{ $push: { "profile.experience" : { exp : "Intermediate" } } }
)
You get this error:
The field 'profile.experience' must be an array but is of type Object
in document {_id: ObjectId('565425f562760dfe14339ba9')}
And if you try (update doc /* 3 */):
db.profile.update(
{ _id: ObjectId("5654260662760dfe14339baa") },
{ $push: { "profile.experience" : { exp : "Intermediate" } } }
)
You will get:
The field 'profile.experience' must be an array but is of type String
in document {_id: ObjectId('5654260662760dfe14339baa')}
i changed Schema like this
experience : [{type:String,exp:String}],
my update object looks like this
var update = {
$push: {
'profile.experience': san.exp
}
};
san looks like this :{ exp: 'YYY' }
Inside mongoose collectionlooks like this used RoboMongo
"experience" : [
"experienced in XXX",
"YYY"
],
$push: {
'profile.experience': experience
}
Remove .exp.
First you have to check you declared your field as an array like this(look at field products):
shop = {
'name': "Apple Store",
'description': "",
'direction': "",
'contact': "",
'products':[]
}
Now if you want to add something to the field products using $push
product = {
'name': "Iphone 6",
'description': "Iphone model 6, 64GB",
'price': 700,
'count': 3
}
myquery = { "name" : "Apple Store" }
obj ={"$push":{"products":{"$each": [product]}}}
db.collection.update_one(myquery,obj)
This code is provided for PyMongo framework. To use in MongoDB directly replace update_one by update. Mongo resource
You may use $set instead of $push which might work.
$set: {
'profile.experience': experience
}
are you searching for adding multiple values into single field then use this one.
write this one your model or schema:
arrayremarks:[{remark: String}]
then write in your controller:
module.exports.addingremarks = (req, res) => {
let casenum=JSON.parse(JSON.stringify(req.body.casenum).replace(/"\s+|\s+"/g,'"'))
var rem={remark:"Suman macha"}
Inwart.update( { 'casenum': casenum },{ $push: { arrayremarks:rem} } ,function (err, inwarts) {
if (err)
return console.error(err);
res.send(inwarts);
}
)
}

Resources