JSON parse returns empty string? - javascript

I am not sure if this is an issue about VueJS or JS itself.
I have string in my DB (converted JS Object with JSON.stringify() ) which looks like this:
{"type":5,"values":{"7":"/data/images/structured-content/64-7-scico.jpg","8":"<b>wefwe</b>","9":"Nějaký text","10":"/data/images/structured-content/64-10-scico.jpg"}}
What I wanted to do is select it from database (via Axios), convert it back to JS object and set it to VueJS data:
.then(response => {
if (response.data.response === "ok" && response.status == 200) {
// get data
let data = response.data.data.data[0];
// pass name to state
this.objectName = data.name;
// get json in string format
let result = data.content;
// first log
console.log(result);
// convert string to json
let content = JSON.parse( result );
// second log
console.log( content.values );
// update states
this.IDType = content.type;
this.values = content.values;
}
})
Axios, data.name and content.type works fine, however the second log (content.values) seems to be returning observer with empty strings which I can't pass to Vue data and work with it, as you can see on the screen below, values in this object are just empty no matter what I do.
What is exactly wrong in here? Thank you!
from debugger:

To be reactive Vue needs to know what the keys of an object are before you assign them. So if they are known, pre assign them:
data : () => ({
values : {
7 : "",
8 : "",
9 : "",
10 : ""
}
}),
Then use object assign to set them:
Object.assign(this.values, content.values)
If the keys are unknown / dynamic values you can set them to be reactive using the $set method:
Object.keys(content.values).forEach(
function(key){
this.$set(this.value, key, content.values[key])
}
)

Related

Complex JSON obj and jQuery or Javascript map to specific key, value

I am banging my head trying to figure this out. And it should not be this hard. I am obviously missing a step.
I am pulling data from: openaq.org
The object I get back is based on a JSON object.
For now, I am using jQuery to parse the object and I am getting to the sub portion of the object that hold the specific parameter I want but I can't get to the specific key,value pair.
The object does not come back in the same order all the time. So when I tried to originally set up my call I did something like
obj.results.measurements[0].
Well since the obj can come back in an random order, I went back to find the key,value pair again and it was the wrong value, throwing my visual off.
That said, I have looked at use jQuery's find() on JSON object and for some reason can not get what I need from the object I am given by openaq.org.
One version of the object looks like this:
{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
I am trying to get the "pm25" value.
The code I have tried is this:
function getAirQualityJson(){
$.ajax({
url: 'https://api.openaq.org/v2/latest?coordinates=39.73915,-104.9847',
type: 'GET',
dataType: "json"
// data: data ,
}).done(function(json){
console.log("the json is" + JSON.stringify(json));
console.log("the json internal is" + JSON.stringify(json.results));
var obj = json.results;
var pm25 = "";
//console.log(JSON.stringify(json.results.measurements[0]["parameter"]));
$.each(json.results[0], function(i,items){
//console.log("obj item:" + JSON.stringify(obj[0].measurements));
$.each(obj[0].measurements, function(y,things){
//console.log("each measurement:" + JSON.stringify(obj[0].measurements[0].value));//get each measurement
//pm 2.5
//Can come back in random order, get value from the key "pm25"
// pm25 = JSON.stringify(obj[0].measurements[2].value);
pm25 = JSON.stringify(obj[0].measurements[0].value);
console.log("pm25 is: " + pm25); // not right
});
});
//Trying Grep and map below too. Not working
jQuery.map(obj, function(objThing)
{ console.log("map it 1:" + JSON.stringify(objThing.measurements.parameter));
if(objThing.measurements.parameter === "pm25"){
// return objThing; // or return obj.name, whatever.
console.log("map it:" + objThing);
}else{
console.log("in else for pm25 map");
}
});
jQuery.grep(obj, function(otherObj) {
//return otherObj.parameter === "pm25";
console.log("Grep it" + otherObj.measurements.parameter === "pm25");
});
});
}
getAirQualityJson();
https://jsfiddle.net/7quL0asz/
The loop is running through I as you can see I tried [2] which was the original placement of the 'pm25' value but then it switched up it's spot to the 3rd or 4th spot, so it is unpredictable.
I tried jQuery Grep and Map but it came back undefined or false.
So my question is, how would I parse this to get the 'pm25' key,value. After that, I can get the rest if I need them.
Thank you in advance for all the help.
You can use array#find and optional chaining to do this,
because we are using optional chaining, undefined will be returned if a property is missing.
Demo:
let data = {"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}
let found = data?.results?.[0]?.measurements?.find?.(
({ parameter }) => parameter === "pm25"
);
console.log(found);
You can iterate over measurements and find the object you need:
const data = '{"meta":{"name":"openaq-api","license":"CC BY 4.0d","website":"https://u50g7n0cbj.execute-api.us-east-1.amazonaws.com/","page":1,"limit":100,"found":1},"results":[{"location":"Metro Lofts","city":null,"country":"US","coordinates":{"latitude":39.731,"longitude":-104.9888},"measurements":[{"parameter":"pm10","value":49.9,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"pm1","value":24,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"},{"parameter":"um100","value":0,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um025","value":0.28,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"um010","value":4.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"particles/cm³"},{"parameter":"pm25","value":41.1,"lastUpdated":"2021-08-09T20:49:38+00:00","unit":"µg/m³"}]}]}';
const json = JSON.parse(data);
let value = null;
const measurements = json?.results?.[0]?.measurements ?? null;
if(measurements)
for (const item of measurements)
if (item.parameter === 'pm25') {
value = item.value;
break;
}
if (value) {
// here you can use the value
console.log(value);
}
else {
// here you should handle the case where 'pm25' is not found
}

localStorage ReactJs not working while push

I just tried to store array data inside localStorage with ReactJs.
Code Below :
storeData(){
const datas = {
name : this.state.prevName,
id : Date.now()
}
var localDatas = localStorage.getItem('names');
if(!localDatas){
localStorage.setItem('names',JSON.stringify(datas));
}else{
var items = [];
items = JSON.parse(localStorage.getItem('names'));
items.push(datas);
localStorage.setItem('names',JSON.stringify(items));
}
}
It's working first time when undefined localDatas variable. I mean when there is no names set at localStorage.
if running for first time And whenever i tried to push new data then its generate error.
Error Below :
TypeError: items.push is not a function
}else{
68 | var items = [];
69 | items = JSON.parse(localStorage.getItem('names'));
> 70 | items.push(datas);
71 | ^ localStorage.setItem('names',JSON.stringify(items));
72 | }
73 | }
How to solve this ?
When first localDatas is undefined, it sets the localStorage item as an object, not array.
Second time this function is called, items is an object and not an array and therefore no .push for him.
var items = []; // items is array
items = JSON.parse(localStorage.getItem('names')); // items is now OBJECT!!
items.push(datas); // can't do a .push to an object
localStorage.setItem('names',JSON.stringify(items));
You could just make datas an array and everything should work.
const datas = [{
name : this.state.prevName,
id : Date.now()
}]
FIX:
Since datas is now an array and we want to push only the object inside, instead of:
items.push(datas); should be: items.push(datas[0]);
The problem is that JSON.parse is returning an object (not an array). As an object it does not have any "push" method.
You could fix this by making sure "datas" is starting as an array :
let storeData = () => {
const datas = [{
name : this.state.prevName,
id : Date.now()
}]
var localDatas = localStorage.getItem('names');
if(!localDatas) {
localStorage.setItem('names',JSON.stringify(datas));
} else {
var items = [];
items = JSON.parse(localStorage.getItem('names'))
items.push(datas);
localStorage.setItem('names',JSON.stringify(items));
}
}
The JSON.parse function returns an object if the string passed to it represents a JSON object, and an array if the string represents a JSON array. If you're using window.localStorage.getItem('names') to retrieve data from local storage and JSON.parse() to parse that data, the type of data returned will depend on the string stored in local storage. From your code, you passed on to the local storage, which is the datas.
If you want to ensure that you get an array, you can modify the data stored in local storage to be a JSON string representing an array like this:
window.localStorage.setItem('data', JSON.stringify([datas]))
In that case
data = JSON.parse(window.localStorage.getItem('data'))
will return array for you to perform push and other array functions.

Is there a way to pass the value attribute of an unsubmitted input field as a parameter of a URL using javascript/Jquery?

I am trying to retrieve the value attribute of an unsubmitted input field as parameter to a URL that opens/saves an excel file. The Parameters are supposed to be used to filter the excel file.
I have tried using a for()-loop to save the parameters into an array and then proceed to use the append() method to add them to the end of the url.
Code below shows how I am trying to singularly append each parameter one after the other
var url = new URL("file:database/reports/getCurrentStorageOverview.php?params=excel");
var query_string = url.search;
var search_params = new URLSearchParams(query_string);
search_params.append('params', $("#searchParameter1").val());
search_params.append('params', $("#searchParameter2").val());
search_params.append('params', $("#searchParameter3").val());
search_params.append('params', $("#searchParameter4").val());
url.search = search_params.toString();
var new_url = url.toString();
window.open("database/reports/getCurrentStorageOverview.php?params=excel");
console.log(new_url);
The parameters are supposed to be added to the end of the url however the console keeps telling me the value attribute is either undefined/ when i was trying to use an array it was filling the array with 4 "undefined(s)"
it's a different aproach but since i haven't tested your method i can show u what i normally use for this case:
const querify = obj => {
return Object.keys(obj)
.map(key => {
if (typeof obj[key] === 'object') {
return querify(obj[key])
} else {
return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`
}
})
.join('&') }
what this does is it takes an object like
var filters = { page: 1, length: 10, sortBy: 'id', etc... }
and turns it into a query string that looks like "page=1&length=10&sortBy=id" etc so u can use it like this:
var url = `database/reports/getCurrentStorageOverview.php?${querify(filters)}`

How to fetch values from json array object without using object key name javascript?

Json Array Object
Through Ajax I will get dynamic data which is not constant or similar data based on query data will change. But I want to display charts so I used chartjs where I need to pass array data. So I tried below code but whenever data changes that code will break.
I cannot paste complete JSON file so after parsing it looks like this
[{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
You can use Object.keys and specify the position number to get that value
var valueOne =[];
var valueTwo = [];
jsonData.forEach(function(e){
valueOne.push(e[Object.keys(e)[1]]);
valueTwo.push(e[Object.keys(e)[2]]);
})
It seems like what you're trying to do is conditionally populate an array based the data you are receiving. One solution might be for you to use a variable who's value is based on whether the value or price property exist on the object. For example, in your forEach loop:
const valueOne = [];
jsonData.forEach((e) => {
const val = typeof e.value !== undefined ? e.value : e.average;
valueOne.push(val);
})
In your jsonData.forEach loop you can test existence of element by using something like:
if (e['volume']===undefined) {
valueone.push(e.price);
} else {
valueone.push(e.volume);
}
And similar for valuetwo...
You could create an object with the keys of your first array element, and values corresponding to the arrays you are after:
var data = [{"brand":"DUNKIN' DONUTS KEURIG","volume":1.9,"value":571757},{"brand":"MC CAFE","volume":1.1,"value":265096}];
var splitArrays = Object.keys(data[0]).reduce((o, e) => {
o[e] = data.map(el => el[e]);
return o;
}, {});
// show the whole object
console.log(splitArrays);
// show the individual arrays
console.log("brand");
console.log(splitArrays.brand);
console.log("volume");
console.log(splitArrays.volume);
// etc

How to get the GET request passed list data?

If I use the params for pass a list in GET method:
fetch_physicalserver_list(){
var params = {
id_list: this.physicalserver_id_list // there is [24, 26, 27]
}
this.$Lml_http('get', this.$Api_urls.user_productmanage_physicalserver.list(), params, response => {
this.physicalserver_list = response.data.results
console.log( response.data.results)
}, error => {
})
}
And in the request, the id_list convert to the id_list[]=24&id_list[]=27&id_list[]=27.
and I don't know how to get the id_list in the backend.
I use the method to get the id_list[] I will only get the first id, if I get id_list, I will get nothing.
the code of get_param_from_query_params method:
def get_param_from_query_params(query_params, param):
param_temp = None
try:
mutable = query_params._mutable
query_params._mutable = True
param_list = query_params.pop(param)
param_temp = param_list[0] if (isinstance(param_list, list) and len(param_list) > 0) else ''
query_params._mutable = mutable
except Exception as e:
pass
return param_temp
So, I have two questions:
1.The params's id_list converted to id_list[]. where is the official description?
2.How can I get the id_list after I passed to the backend?
Firstly, you are using the key id_list[], so you must use id_list[] to retrieve the key in Django. Including [] in JavaScript is a convention to show there are multiple values, but it makes no difference to Django.
If you want a list of values instead of a single value, then use pop_item instead of pop.
It's not clear to me why you need the get_param_from_query_params method. You are returning param_list[0] which means you'll only ever get a single item. It would be much simpler to use getlist:
id_list = query_params.getlist('id_list')

Categories