How can I accesss to the elements of array objects? - javascript

How Can I get data from this json data ?
I get this data from the server, and it sends some database's datas by using sequelize.
Data what I want to access is
{result: "[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]"}]" }
And I tried console.log(result[0].userid);
But, I only got errer like this. ' Uncaught TypeError: Cannot read property 'userid' of undefined'.
Could you tell me what I have to fix?

You gave an invalid JSON, the json should be something like this:
Formatted JSON Data
{
"result":[
{
"userid":"a",
"speed":10
},
{
"userid":"b",
"speed":20
},
{
"userid":"c",
"speed":30
}
]
}
And after that you can access it:
const json = {
"result":[
{
"userid":"a",
"speed":10
},
{
"userid":"b",
"speed":20
},
{
"userid":"c",
"speed":30
}
]
};
console.log(json.result[0].userid);

Your JSON is badly formatted.
Try this instead...
{"result":[{"userid":"a","speed":10},{"userid":"b","speed":20},{"userid":"c","speed":30}]}
The main issues were...
{result: "[{"userid"
Should be...
{"result":[{"userid"
And
"speed":30}]"}]" }
Should be...
"speed":30}]}
Please note, the whitespace between the items makes no difference, but I have remove to reduce the size of the JSON string

Related

How do I export complex json data to excel/google sheet

I am getting the following Json string from Firebase Realtime database.
{
'algotable': {
'-NJ6blqyqu8RgjvdQJyT': {
'actual': '123',
'cipher': '39bc62c2ad990f494e0ad2b5715a3f05',
'decrypted': '123'
},
'-NJ6bmsPnb1GNi_jYyPb': {
'actual': 'abcd',
'cipher': '39bc62c2ad990f494e0ad2b5715a3f05',
'decrypted': 'abcd',
}
}
}
I tried importing json file in micrsoft excel but it shows only two columns without any data i.e. algotable,records
I tried google appscript
console.log(string1.algotable.getData);
but I don't get any output because object inside algotable always changes its name whenever I push an object through android-java as below
public String writeNewRecordEncrypt(Algotable algotable) {
DatabaseReference pushref = mDatabase.push();
pushref.setValue(algotable);
return pushref.getKey();
}
please help me amend this. thanks in advance

How to parse an string into more workable key-values?

So I have the following response:
{
"errors": [
{
"errorKey": "ERROR_NO_DELIVERY_OPTIONS",
"errorParameters": "[{\"errorMessage\":\"ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW\",\"partNumbers\":[\"19308033\",\"19114798\"]},{\"errorMessage\":\"Pickup At Seller not available for these orderItemIds\",\"orderItemIds\":[\"10315031\",\"10315032\"],\"availableShipModeId\":\"13201\"}]",
"errorMessage": "ERROR_NO_DELIVERY_OPTIONS",
"errorCode": "ERROR_NO_DELIVERY_OPTIONS"
}
]
}
Unfortunately, I'm not sure how to work with the value of "errorParameters" since it just a string and not a simple key-value like the others. How would I extract all the information so I can work with it. A co-woker mentioned parsing it but not sure what he meant by that and how. Below is a more readable value. I'm working with javascript.
[
{
"errorMessage": "ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW",
"partNumbers":
[
19308033,
19114798
]
},
{
"errorMessage": "No Shipmodes Available for these orderItemsIds",
"orderItemIds": [
10315031,
10315032
]
}
]
You will need to use JSON.parse to transform JSON strings into a JS Object.
You'll need to do this in your code. I.E.
data.errors.forEach(e => console.log(JSON.parse(e.errorParameters)))
You can use just JSON.parse() function, which changes string JSON representation into a JavaScript object.
const parsedErrorParameters = JSON.parse(data.errorParameters);
console.log(parsedErrorParameters[0].errorMessage); // ERROR_DELIVERY_OPTIONS_YOU_SELECTED_NOT_AVAILABLE_NOW
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

How to get more data with axios?

when I do this:
const uuidapi = await axios.get('https://api.hypixel.net/player?key=mykey&name=' + args[1]);
console.log(uuidapi);
I get this response from Axios:
https://paste.menudocs.org/paste/7vppu
So my question is: How do I get the Data after "socialMedia"? Heres how socialMedia looks like:
"socialMedia": {
"links": {
"YOUTUBE": "https://www.youtube.com/channel/UC1L7H9qQyB2zZgt-1XUv6jA",
"DISCORD": "Altpapier#4847"
}
}
Why does it say socialMedia: [Object], and how do I get more than this?
I can't use const { data } = await axios.get(URL); because I want to get 2 URL responses with the complete data.
I also want to be able to safe for example the DISCORD Name Altpapier#4847 how do I do that?
All the data is already here, it's just the formatting of console.log that's not printing every nested object.
If you replace
console.log(uuidapi);
by
console.log(JSON.stringify(uuidapi));
it will work better
See this question: How can I get the full object in Node.js's console.log(), rather than '[Object]'?
you can use console.dir( yourObject, { depth: null } )

How to acces to specific properties into a JSON or Object in JavaScript

I'm making an app in Nodejs using express and node-xlsx module, what I want to do is to make the user able to upload an xlsx file (which has to have an specific format of two columns), an then the server reads it and does something with each row of the file.
(Example of my test file, being the columns A and B respectively):
Johny Wilson | jonhny#email.com
Andrew Jehnsen | andrew#example.com
Billy Soon | billy#mail.com
In order to do this, I've decided to use the node-xlsx module, which, after reading the file with this code:
var xlsx = require('node-xlsx');
router.post('/enviar', upload.single("lista"),(req, res, next) =>{
//dir is the path of the xlsx file
const workSheetsFromFile = xlsx.parse(dir);
res.send(workSheetsFromFile);
});
returns an object that looks like this:
[
{
"name": "Hoja1",
"data": [
[
"Johny Wilson",
"jonhny#email.com"
],
[
"Andrew Jehnsen",
"andrew#example.com"
],
[
"Billy Soon",
"billy#mail.com"
]
]
}
]
As you can see, the module returns the data of all the file, including the sheet's details (In this case only one), I want to access only to the 'data' array which contains keys and values to process them.
I've already tried to loop on the data array with:
workSheetsFromFile.data.forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile[data].forEach((element) =>{
console.log(element);
});
and
workSheetsFromFile['data'].forEach((element) =>{
console.log(element);
});
but all of them just send me an error like "Cannot read property 'forEach' of undefined" or "data is not defined" :(
For now, with those few lines of code I was specting to iterate the data array and print each pair of key and value, so once that is fixed, inside this loop process each key and value in order to send automated mails.
What you have here seems to be an array of objects, not an object itself!
try
workSheetsFromFile[0].data.forEach((element) => {
console.log(element);
});
If you have more elements, consider first looping the array and then extracting data
const structuredData = workSheetsFromFile[0].data.map(res => {
return res
});
workSheetsFromFile.forEach(sheet => {
//access data
console.log(sheet.data)
//or
sheet.data.forEach(data => {
//access each data
console.log(data)
})
})

Remove the parent element from JSON reply

I have a route used for AJAX calls. It gets items from a DB and returns a JSON array.
I'm using:
return reply({
myArray
}).code(200);
Everything works but my output in the browser is:
{
"myArray":[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
}
But what I need is:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
Very basically, I need to get rid the "myArray" parent element and leave just the array there. It looks like a simple task but I can't find documentation or samples anywhere.
Thanks,
Marco
This:
{
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
}
is invalid JSON notation. Within curly braces, you should have key-value pairs where keys are strings and values are valid JSON values (strings, numbers, booleans, null, arrays, or objects).
Perhaps what you expect is just the array:
[
{
"_id":"1",
"name":"Asd1"
},
{
"_id":"2",
"name":"Asd2"
}
]
which is valid JSON. In this case, you may simply send it to your reply function:
return reply(myArray).code(200);
For more info on JSON notation, see the article on MDN and play with JSON.stringify to develop better intuition on when the JSON you see is valid or not.

Categories

Resources