JSON only reading first element of array - json

I am working on a discord bot using Typescript, and I am having a problem reading from the config.JSON file.
This is the read vars function:
fs.readFile('config.json', 'utf8', function readFileCallback(err, data){
if (err){
console.log(err);
} else {
config = JSON.parse(data);
console.log(config);
const store = config.configstore[0];
roster = config.roster[0];
}});
and this is the config.json file:
{
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
When I print out the raw 'config' variable it prints this:
{
configstore: [
{ prefix: '!!' },
{ wallTime: 5 },
{ bufferTime: 15 },
{ wall: 'false' },
{ buffer: 'false' },
{ lastWallTime: '-1' },
{ lastBufferTime: '-1' },
{ wallCheckRole: 'Role' },
{ bubfferCheckRole: 'Role' }
],
roster: [ { discID: 'DiscordID', ign: 'IGN' } ]
}
But when I print the store variable it prints this:
{ prefix: '!!' }
The roster is normal as well.
The roles and ids are strings, but I changed it since I don't want them leaked.

These are some examples of what you are probably trying to achieve:
let config1 = {
"configstore": [
{"prefix": "!!"},
{"wallTime": 5},
{"bufferTime": 15},
{"wall": "false"},
{"buffer": "false"},
{"lastWallTime": "-1"},
{"lastBufferTime": "-1"},
{"wallCheckRole": "Role"},
{"bubfferCheckRole": "Role"}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
let config2 = {
"configstore": [
{
"prefix": "!!",
"wallTime": 5,
"bufferTime": 15,
"wall": "false",
"buffer": "false",
"lastWallTime": "-1",
"lastBufferTime": "-1",
"wallCheckRole": "Role",
"bubfferCheckRole": "Role"
}
],
"roster": [
{"discID":"discordID","ign":"IGN"}
]
}
//prints {"prefix":"!!"}
console.log("configstore1:", JSON.stringify(config1.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster1:", JSON.stringify(config1.roster[0]));
//prints {"prefix":"!!","wallTime":5,"bufferTime":15,"wall":"false","buffer":"false","lastWallTime":"-1","lastBufferTime":"-1","wallCheckRole":"Role","bubfferCheckRole":"Role"}
console.log("configstore2:", JSON.stringify(config2.configstore[0]));
//prints {"discID":"discordID","ign":"IGN"}
console.log("roster2:", JSON.stringify(config2.roster[0]));

Related

How to transform complex json structure using Groovy?

first of all, thanks for your time!
So i've been using Groovy for a couple of weeks now but i can't seems to be able to transform the following json structure:
{
"collection_1": [
[
"value_1",
"value_2",
"value_3"
],
[
"value_1",
"value_2",
"value_3",
"value_4"
]
],
"collection_2": [
[
"value_1",
"value_2",
"value_3",
"value_4",
"value_5"
]
],
"collection_3": [
[
"value_1",
"value_2"
]
]
}
To something like:
{
"collection_1": [
[
"value_1": false,
"value_2": false,
"value_3": false
],
[
"value_1": false,
"value_2": false,
...
Here is how i did it:
Map<String, Object> getSelectableItems(Map<String, Object> jsonDeserialized) {
def selectableItems = [:]
jsonDeserialized.each { collection, subCollection ->
selectableItems.put(collection, [:])
subCollection.eachWithIndex { items, index ->
selectableItems.get(collection).putAt(index, items.collect { value ->
[
"${value}" : false
]
})
}
}
return selectableItems
}
​
I've been trying for days, it isn't that hard, i even succeed but the final code is looking terribly wrong.
Do you have any idea of how I could achieve something like so with the power of Groovy?
Thanks groovy pros :D
import groovy.json.*
def data = new JsonSlurper().parseText('''
{...your json here...}
''')
data.replaceAll { k, v -> v = v.collect { it.collectEntries { [it,false] } } }
println new JsonBuilder(data).toPrettyString()
output:
{
"collection_1": [
{
"value_1": false,
"value_2": false,
"value_3": false
},
{
"value_1": false,
"value_2": false,
"value_3": false,
"value_4": false
}
],
"collection_2": [
{
"value_1": false,
"value_2": false,
"value_3": false,
"value_4": false,
"value_5": false
}
],
"collection_3": [
{
"value_1": false,
"value_2": false
}
]
}

setstate() with list.lengh parameter didn't work

I tried to count the number of items in my list "data"
my component looks like that :
BuildMap() {
axios.post('http://104.xx.xx.xxx:8081/children', {action: "list"}, {headers: {'x-access-token': this.props.base.Token}})
.then(res => {
const data = res.data;
this.setState({data, NbrProfil: data.length});
})
.catch(err => console.log(err));
}
"data" is correctly returned and here is what it's return :
[
{
"name": "Mia",
"age": 12,
"options": [],
"discordId": "12",
"alerts": 0,
"warnings": 0
},
{
"name": "Demetra",
"age": 12,
"options": [],
"discordId": "12",
"alerts": 0,
"warnings": 0
}
]
sadly "NbrProfil" stay undefined and could be "2" ...
can I have some help please ?

How to export the api call results to a csv with the values of single response in one row?

My api response looks like below
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
Now in react, I want to export the results to a csv. I can do it by export-to-csv but the formatting is the issue here. I want the values of each question of a single response in one row under their labels(questions). So if I have two response like above I want to have export it in two rows, not 8 as there are 8 total questions.
Here is how I want it to get exported.
I have tried so far like this but no luck.
this is my export data function
exp =()=>{
const raw = []
console.log(this.state.data[0].sbm_id)
axios.get(`/dashboard/${this.props.proj_id}/whole_sub/`)
.then(res=>{
// console.log('1')
// console.log(res.data[0][0])
// console.log('2')
for (let i =0;i<this.state.data.length;i++){
for(let j = 0;j<res.data[0].length;j++){
// let sub=[]
//res.data[i][j].ID = this.state.data[i].sbm_id
raw.push(res.data[i][j])
}
}
}
)
let curr = this.state
curr.exp = raw
this.setState({exp:curr.exp})
}
Here is my export function
rawExport=()=>{
const csvExporter = new ExportToCsv(optionsExp);
csvExporter.generateCsv(this.state.exp);
}
First step is to flatten the initial nested array to get a homogeneously shaped array, then you keep on reducing it further.
const data = [
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"2050"
]
},
{
"How much do you sleep?": [
"Ajajajsjiskskskskdkdj"
]
}
],
[
{
"What time is it?": [
"option_2"
]
},
{
"When will we go home?": [
"option_1"
]
},
{
"When is your birthday?": [
"10181"
]
},
{
"How much do you sleep?": [
"Ajskossooskdncpqpqpwkdkdkskkskskksksksksks"
]
}
]
];
const flattenArray = (arr) => [].concat.apply([], arr);
// Flatten the initial array
const flattenedArray = flattenArray(data);
// Keep on reducing the flattened array into an object
var res = flattenedArray.reduce((acc, curr) => {
const [key, val] = flattenArray(Object.entries(curr));
if (!acc[key]) {
acc[key] = [].concat(val);
} else {
val.forEach(x => {
if (!acc[key].includes(x)) {
acc[key].push(x);
}
});
}
return acc;
}, {});
console.log(res);

Angular/Ionic - How to group data from two JSON source?

I want to group data JSON into accordion list in Ionic. How can I do that with two JSON source?
Previously I did successfully with only one JSON.
I have two JSON that look like this.
The one :
{
{
"ObjectId": '001',
"ObjectName": 'Fruits'
},
{
"ObjectId": '002',
"ObjectName": 'Vegetables'
}
}
The other one :
{
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
},
}
Here my expected result image :
Accordion-List
I've found the solution, but i'm not sure my method is the best way.
Here is my method :
// GET DATA API
let getObjectApi = this.dataProvider.getObjectUrl();
new Promise(resolve => {
getObjectApi.subscribe(data => {
resolve(data);
this.apiObjectData = data;
// LOOPING OBJECT DATA
for (let i = 0; i < this.apiObjectData.length; i++) {
const objItem = data[i];
// GET OBJECT ITEM BY ObjectId
let getObjectItem = this.getObjectItemByObjectId('ObjectId', objItem['ObjectId']);
// PUSH THE DATA
this.apiDataResult.push({
'dataObject': objItem,
'dataObjectItem' : getObjectItem
});
}
}, err => {
console.log(err);
});
});
And here this.getObjectItemByObjectId() method :
getObjectItemByObjectId(column, value) {
let result:any = [];
let dataApi: any = [];
let getObjectItemApi = this.dataProvider.getObjectItemUrl();
new Promise(resolve => {
getObjectItemApi.subscribe(data => {
resolve(data);
dataApi = data;
for (let i = 0; i < dataApi.length; i++) {
const element = dataApi[i];
if (element[column] == value) {
result.push(element);
}
}
}, err => {
console.log(err);
});
});
return result;
}
And the result is something like this :
{
{
"dataObject": {
"ObjectId": '001',
"ObjectName": 'Fruits'
},
"dataObjectItem": {
{
"Name": 'Apple',
"Color": 'Red',
"ObjectId": '001'
},
{
"Name": 'Banana',
"Color": 'Yellow',
"ObjectId": '001'
}
}
},
{
"dataObject": {
"ObjectId": '002',
"ObjectName": 'Vegetables'
},
"dataObjectItem": {
{
"Name": 'Eggplant',
"Color": 'Purple',
"ObjectId": '002'
},
{
"Name": 'Spinach',
"Color": 'Green',
"ObjectId": '002'
},
{
"Name": 'Garlic',
"Color": 'White',
"ObjectId": '002'
}
}
}
}
That's all!
If there is a better way than my method, please let me know! And sorry if something is goes wrong. Thank you in advance !!

Iterate through JSON Object to get all objects with property

I am trying to iterate through the following JSON document in order to get the names of skating rinks:
I can get one name; however, what I am trying to do is loop through all of the entries (there are 253) and return a list of all the names.
Here is my React component:
class Patinoire extends Component {
constructor(props) {
super(props);
this.state = { patinoires: [] };
}
componentDidMount() {
var url = 'http://localhost:3000/patinoires'
fetch(url).then(function(response) {
if (response.status >= 400) {
throw new Error("Bad response from server");
}
return response.json();
})
.then(data => this.setState ({ patinoires: data.patinoires }));
}
render() {
var patinoires = this.state.patinoires;
var pjs2 = Object.values(patinoires);
var pjs3 = pjs2.map(x => x["2"].nom);
return <div>{pjs3}</div>
}
}
Right now, when using {pjs3}, I get the name of 3rd skating rink of the JSON document. How can I loop through all the entries and return the name property of all the entries?
EDIT: here is a sample of the data
{
"patinoires": {
"patinoire": [
{
"nom": [
"Aire de patinage libre, De la Savane (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
},
{
"nom": [
"Aire de patinage libre, Georges-Saint-Pierre (PPL)"
],
"arrondissement": [
{
"nom_arr": [
"Côte-des-Neiges - Notre-Dame-de-Grâce"
],
"cle": [
"cdn"
],
"date_maj": [
"2018-01-12 09:08:25"
]
}
],
"ouvert": [
""
],
"deblaye": [
""
],
"arrose": [
""
],
"resurface": [
""
],
"condition": [
"Mauvaise"
]
}
]
}
}
You can use Array.prototype.reduce() to flatten the result data with combination of Array.prototype.map() or Array.prototype.forEach().
Here is a running example:
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
patinoires: {
patinoire: [
{
nom: ["Aire de patinage libre, De la Savane (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
},
{
nom: ["Aire de patinage libre, Georges-Saint-Pierre (PPL)"],
arrondissement: [
{
nom_arr: ["Côte-des-Neiges - Notre-Dame-de-Grâce"],
cle: ["cdn"],
date_maj: ["2018-01-12 09:08:25"]
}
],
ouvert: [""],
deblaye: [""],
arrose: [""],
resurface: [""],
condition: ["Mauvaise"]
}
]
}
};
}
renderData = () => {
const { patinoires } = this.state;
const markup = patinoires.patinoire.reduce((result, current) => {
current.nom.map(n => {
return result.push(<div>{n}</div>);
});
return result;
}, []);
return markup;
}
render() {
return <div>{this.renderData()}</div>;
}
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
Try this:
var pjs2 = Object.values(patinoires);
var names = pjs2.reduce((accumulator, elem) => {
if (elem.patinoire) {
elem.patinoire.forEach(part => {
if(part.nom) {
part.nom.forEach((name) => accumulator.push(name));
}
});
}
return accumulator;
}, []);