Angular Update value in localStorage - arrays

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);
}
}

Related

Kotlin Gson parsing Json Object and Array

I am pretty new to Kotlin and Json and on my work I use GSON to parse the Json.
I need to parse the following Json file into a Class by using GSON.
{
"apiKey": "blablabla",
"baseUrl": "blablabla",
"requestData": [
{
"lng": "6.971",
"lat": "50.942",
"rad": "1.5",
"type": [
"diesel",
"super"
]
},
{
"lng": "6.442",
"lat": "51.180",
"rad": "1.5",
"type": [
"diesel",
"super"
]
},{
"lng": "7.136",
"lat": "50.991",
"rad": "1.5",
"type": [
"diesel",
"super"
]
}
]
}
Now I tried to make a data class like this:
data class ApiParameterData(
var apiKey: String? = null,
var baseUrl: String? = null,
var requestData: String? = null) {
}
I also made another class to store the Json informations in it like this:
class Tankstelle: JsonDeserializer<ApiParameterData> {
override fun deserialize(json: JsonElement?, typeOfT: Type?, context: JsonDeserializationContext?
): ApiParameterData {
json as JsonObject
val apiKey = json.get("apiKey").asString
val baseUrl = json.get("baseUrl").asString
val requestDataJson = json.get("requestData")
val requestData = if (requestDataJson.isJsonObject) requestDataJson.asJsonObject.toString() else requestDataJson.toString()
return ApiParameterData(apiKey, baseUrl, requestData)
}
}
I tried to call it like that:
val gsonConfig = GsonBuilder().registerTypeAdapter(ApiParameterData::class.java, Tankstelle()).create()
val tanke = gsonConfig.fromJson(readJson, ApiParameterData::class.java)
println(tanke.requestData?.get(0))
But of course the output I get is "[" . I think because I get back a String or something and this is the first symbol of it?
I need to loop trough the requestData list and store it as a instance of a class and need to access each different value.
The thing is that I want to give the Json file different places and ranges it should look for gasstations. By reading the Json it should take all the pieces and create a link for each place I write in the requestData list. So in this case I would need 3 different links at the end. But this is another part I can do myself. I just don't know how to parse it so I can access and store every value in this Json.
Thank you already and have a great weekend!
If you need more informations just let me know
First you need to define two types that map to your JSON structure
class ApiParameterData(
val apiKey: String,
val baseUrl: String,
val requestData: List<RequestObject>
)
class RequestObject(
val lng: String,
val lat: String,
val rad: String,
val type: List<String>
)
Now simply parse it as
val apiData = Gson().fromJson(readJson, ApiParameterData::class.java) // No need to add TypeAdapter
// To get requestData
val requestData = apiData.requestData
requestData.forEach {
print("${it.lng}, ${it.lat}, ${it.rad}, ${it.type})
}

Converting a typescript class object with dictionary to a JSON array

After some digging I decided my backend needed to consume duplicate keys and as a consequence my frontend can no longer send a dictionary as a JSON string.
See my previous question.
After applying the solution provided
let mediatagRequest = new MediaTagRequest(tags);
const headers = { 'content-type': 'application/json' }
let jsonObject = {};
for (let entry of mediatagRequest.tags.entries())
{
jsonObject[entry[0]] = entry[1];
}
const body = JSON.stringify({
tags: jsonObject
});
My current output (which is what I then wanted)
{
"tags": {
"city": "Karachi"
}
However my needs have changed and after a bit of of struggle I couldn't get my desired output to be like this
{
"tags": [
{
"key": "city",
"value": "Karachi"
},
{
"key": "city",
"value": "Mumbai"
}
]
}
Could someone help, thank you.
To get your desired output you could use the Object.entries() function to get the key, value pairs separately. This code segment will turn an object into a list of objects with key value pairs:
test_object = {
karachi: "dubai",
mumbao: "moscow",
};
output = Object.entries(test_object).map(([key, value]) => ({ key, value}));
console.log(output);
You can adapt this code to select the desired parts of your object and format them as you like. There are other Object functions you can see in the documentation.

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

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()

Push into Array from Json Angular 5

I'm receiving from an endpoint the following response
{
"data": [{
"volume": 4.889999866485596,
"name": "Carton03",
"weight": 5.75,
"storage": 3
}, {
"volume": 2.6500000953674316,
"name": "Carton02",
"weight": 4.5,
"storage": 2
}, {
"volume": 1.4500000476837158,
"name": "Carton01",
"weight": 5,
"storage": 1
}],
"response": "true",
"type": "Storages"
}
Below I'm trying to create an array at my component:
export class StorageComponent {
private data: any;
private stors: Storage [];
constructor (private storageService: StorageService ) {}
storage () {
this.data = this.storageService.Storage();
//storageService.Storage is an assistant service that parse the response
// and brings me back only the data-array of the response
for (let i = 0; i < this.data.data.length; i++) {
const storages = this.data.data[i];
console.log(storages.storage);
console.log(storages.name);
console.log(storages.weight);
console.log(storages.volume);
this.stors[i] = storages;
}
}
}
I have a const storages to examine that i can evaluate data
and everything is ok.
The problem is that I want to fill up my variable stors that is an array of Storage model which has these attributes , storage,name etc.
I'm trying to do that through the last line but something is wrong ,
getting :
Cannot set property '0' of undefined
Any ideas?
The error is saying that during the first iteration of the loop, the assignment to this.stors[0] is not possible because it is undefined. The stors property has not been initialized. Consider:
constructor (private storageService: StorageService) {
this.stors = [];
}
Just do an initialization when defining the stors property like this:
private stors: Storage[] = [];
you can initialize other properties as well:
private data: any = null;
you may initialize this in the constructor or ngOnInit, but I think it's a better way like this to initialize arrays directly in the properties.
Initializing your class properties will avoid this type of behavior.

How to create json object dynamically from UI using values from input fields before sending to API

I have a http.post request which sends an object as a parameter, the expected format is like this:
var searchQuery;
var subj;
var body;
var startDate;
var endDate;
{
"search": {
"scope": [2,3,32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
The problem is some values are optional meaning that if I don't provide searchQuery as a string then the whole key value should be ingnored, e.g "value": searchqery should be not included in the json object if I did not provide value to that variable. Same goes for startDate and endDate if I don't provide values then date shouldbe ignored from the json.
So how to dynamically include or exlude key pair value in the object that coming from UI and how to build that object before sending to a post request?
Whould it be something like this?
var search = {};
search.text = { value: "", fields: [] };
{value: "", fields: Array(0)}
seach.text.value = "wes";
search.text.value = "wes";
search.text.fields.push("subject");
search.text.fields.push("body");
You can create a function that's a bit more flexible.
var searchQuery = "";
var subj = null;
var body = "";
var startDate = "";
var endDate = null;
let obj = {
"search": {
"scope": [2, 3, 32],
"type": "basic",
"text": {
"value": searchQuery, //string variable coming from UI
"fields": [
subj, body //string variable coming from UI
]
},
"date": {
"type": "range",
"from": startDate, //string variable coming from UI
"to": endDate //string variable coming from UI
}
}
}
function removeNull(obj) {
return Object.keys(obj).reduce((res, key) => {
if (Array.isArray(obj[key])) {
// If it's an array, filter out the null items
res[key] = obj[key].filter((item) => item != null && item !== "");
} else if (typeof obj[key] === "object" && obj[key] != null) {
// If it's an object, call the function recursively
res[key] = removeNull(obj[key]);
} else if (obj[key] != null && obj[key] !== "") {
// Otherwise, only add it to the results if it's not null
res[key] = obj[key];
}
return res;
}, {});
}
console.log(removeNull(obj));

Resources