I have a string array of objects coming to a react native frontend. I'm not sure how to convert this to a json to read it in front end. This is the string I need to convert:
[{_id=63c1400ae18737cd3c67d8d4, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T20:26:54.150Z, timezone=Asia/Seoul, code=11820, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}, {_id=63c12467e18737cd3c67d809, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T15:03:53.000Z, timezone=Asia/Seoul, code=10080, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}]
let stringArr =
'[{_id=63c1400ae18737cd3c67d8d4, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T20:26:54.150Z, timezone=Asia/Seoul, code=11820, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}, {_id=63c12467e18737cd3c67d809, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T15:03:53.000Z, timezone=Asia/Seoul, code=10080, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}]';
console.log("given array -> ",stringArr)
stringArr = stringArr.replace('[', '').replace(']', '').slice(1).slice(0, -1).split(',');
stringArr = stringArr.map(e => {
const trimString = e.trim();
const equalSpilt = trimString.split('=');
const key = equalSpilt[0];
const obj = {};
obj[key] = equalSpilt[1];
return obj;
});
console.log("final output -> ",stringArr)
possible if you can convert your array to string
let stringArr =
'[{_id=63c1400ae18737cd3c67d8d4, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T20:26:54.150Z, timezone=Asia/Seoul, code=11820, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}, {_id=63c12467e18737cd3c67d809, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T15:03:53.000Z, timezone=Asia/Seoul, code=10080, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}]';
stringArr = stringArr.replace('[', '').replace(']', '').slice(1).slice(0, -1).split(',');
stringArr = stringArr.map(e => {
const trimString = e.trim();
const equalSpilt = trimString.split('=');
const key = equalSpilt[0];
const obj = {};
obj[key] = equalSpilt[1];
return obj;
});
You can achieve it like this:
let strval =
"[{_id=63c1400ae18737cd3c67d8d4, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T20:26:54.150Z, timezone=Asia/Seoul, code=11820, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}, {_id=63c12467e18737cd3c67d809, user_id=1185.0, device_serial=544008293, site_id=2000000.0, datetime=2023-01-13T15:03:53.000Z, timezone=Asia/Seoul, code=10080, offset=3.24E7, __v=0.0, device_name=544008293, user_name=sanj, user_key=7722352345}]";
strval = strval.replace("[", "").replace("]", "");
const splittedObj = strval.split("},");
let arr = [];
splittedObj.forEach((e, i) => {
e = e.replace("{", "").replace("}", "");
let obj = {};
e.split(",").map((element) => {
const splittedElement = element.trim().split("=");
obj[splittedElement[0]] = splittedElement[1];
});
arr.push(obj);
});
console.log(arr);
Related
I am using xlsx library to convert input excel file into JSON and it works fine but when I test on android it won't trigger reader.onload function. Please suggest to me what's the correct library to use for android or what to need to change
const reader: FileReader = new FileReader();
reader.readAsBinaryString(file);
reader.onload = (e: any) => {
console.log(e)
const binarystr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
const data = XLSX.utils.sheet_to_json(ws);
console.log(data);
this.fileData = data;
};
It doesn't print console.log(e), I've tried try-catch to catch the error but it didn't catch the error as well. Please let me know what's the issue and which library is best for Android as well as IOS
I solved it. Please see the code below, hope it will help someone
incomingfile(event){
this.file= event.target.files[0];
this.readXLSX(this.file);
}
readXLSX(file){
let fileReader = this.getFileReader(file);
fileReader.onload = (e: any) => {
/* create workbook */
const binarystr: string = e.target.result;
const wb: XLSX.WorkBook = XLSX.read(binarystr, { type: 'binary' });
/* selected the first sheet */
const wsname: string = wb.SheetNames[0];
const ws: XLSX.WorkSheet = wb.Sheets[wsname];
/* save data */
const data = XLSX.utils.sheet_to_json(ws); // to get 2d array pass 2nd parameter as object {header: 1}
console.log(data); // Data will be logged in array format containing objects
this.zone.run(() => {
this.fileData = data;
});
};
}
getFileReader(file): FileReader {
const fileReader = new FileReader();
fileReader.readAsBinaryString(file);
const zoneOriginalInstance = (fileReader as any)["__zone_symbol__originalInstance"];
return zoneOriginalInstance || fileReader;
}
I'm new to Dart/Flutter.
I don't know how to count items from a 2d list.
List<List<bool>> a = [
[true, true, false, false],
[true, false, false, true]
];
I want to count true in this list, but in vertically.
So I want a result like this:
result = [2, 1, 0, 1]
Thank you!
you can use the spread operator to assign length of inner list to a resultant array like this
void main() {
const a = [
[true, true, false],
[true, false, false, true, true]
];
var result = [];
for(var element in a) {
var count = 0;
for (var el in element) {
if (el) {
count += 1;
}
}
result = [...?result,count];
}
print(result);
}
try this code in Dartpad
extension on List<bool> {
List<int> addIfTrue(List<int> counter) {
if (counter.length == length && counter.isNotEmpty) {
var i = 0;
forEach((e) => e ? counter[i++]++ : i++);
return counter;
}
return [];
}
}
void main() {
var a = [
[true, true, false, false],
[true, false, false, true]
];
var n = a[0].length;
var z = a.fold<List<int>>(List.filled(n, 0), (prev, e) => e.addIfTrue(prev));
print(z);
}
Result:
[2, 1, 0, 1]
I'm trying to fetch an API in kotlin with volley, but once I try to get the string from the object, I get nothing returned: W/System.err: org.json.JSONException: No value for burned
This is the API:
"requested_information": [
{
"level": 1,
"character": "一",
"kana": "いち",
"meaning": "one",
"user_specific": {
"srs": "burned",
"srs_numeric": 9,
"unlocked_date": 1464639834,
"available_date": 0,
"burned": true,
try {
val jsonArray = response.getJSONArray("requested_information")
for (i in 0 until jsonArray.length()) {
val jsonObject = jsonArray.getJSONObject(i)
// Append character to textView here
val cha = jsonObject.getString("character")
val burn = jsonObject.getString("user_specific")
val burn2: Boolean = jsonObject.getBoolean("burned")
I have this block of code that handles the component's state:
componentWillMount(){
this.state = {
datasource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2})
}
db.transaction((tx) => {
tx.executeSql("SELECT * FROM schedules", [], (tx, res) => {
let len = res.rows.length;
if(len > 0) {
for(let i = 0; i < len; i++) {
obj.push({id: res.rows.item(i)["id"], title: res.rows.item(i)["title"]})
}
this.setState({
datasource: this.state.datasource.cloneWithRows(obj)
})
var data = this.state.datasource;
console.log(data);
} else {
console.log("empty")
}
})
}, (err) => {
console.log("error: " + JSON.stringify(err))
})
}
It works like a charm when the app launches the first time. But whenever I re-enter the page again the values inside datasource get duplicated. Shouldn't rowHasChanged: (row1, row2) => row1 !== row2 force the ListView not to behave like that or am I missing a logic that needs to be added to the code?
ListView bug example:
========================
| First title, id: 1 |
========================
| Second title, id: 2 |
========================
| First title, id: 1 |
========================
| Second title, id: 2 |
When I console logged the datasource I saw this property: _cachedRowCount:15
Is there a way to force react native not to cache this.state.datasource and re-run every time the page gets open?
I ended up solving that issue by emptying the obj array like so:
db.transaction((tx) => {
tx.executeSql("SELECT * FROM schedules", [], (tx, res) => {
let len = res.rows.length;
if(len > 0) {
for(let i = 0; i < len; i++) {
obj.push({id: res.rows.item(i)["id"], title: res.rows.item(i)["title"]}) // Array that needs to be emptied
}
this.setState({
datasource: this.state.datasource.cloneWithRows(obj)
})
obj = [] // Done here
}
})
}, (err) => {
console.log("error: " + JSON.stringify(err))
})
My goal is it to create a search ListView with JSON Data.
This is working but I have a tiny problem with the search function.
When I type in a word, it has to be exactly the same word, which is in the Array of the ListView.
The main problem is that I have to type in the correct word.
For example: when the word stackoverflow is one item of the Array, I have to type in stackoverflow to find this item.
But I want to get the Item also when I type in stack or flow or stacko for example.
This is my code:
filterDatasource(event)
{
var searchString = event.nativeEvent.text.toLowerCase();
if (searchString != "")
{
var content = this.state.loadedContent;
var searchResultsArray = [];
for (var i = 0; i < content.length; i++) {
var detailArray = content[i];
const gattung = detailArray.Gattung;
const zugnummer = detailArray.Zugummer;
const ab = detailArray.ab;
const bis = detailArray.bis;
const wochentag = detailArray.Wochentag;
const zeitraum = detailArray.Zeitraum;
if (searchString.contains(ab.toLowerCase())) //searchString.indexOf(ab) >= 0
{
//alert('gefunden');
searchResultsArray.push(detailArray);
this.setState({ dataSource: ds.cloneWithRows(searchResultsArray) });
}
}
}
else {
this.setState({ dataSource: ds.cloneWithRows(this.state.loadedContent) });
}
},
You can do this with indexOf like this:
if (searchString.indexOf(ab.toLowerCase()) > -1)
{
...
}