How can I read a JSON without parent root name with JavaScript? - javascript

I have a JSON file which has this:
[
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
]
As you can see it doesn´t have any parent root name. How can I read this JSON with JavaScript ?
I was thinking to PARSE the Json but JSON.parse(need the name)
Is it possible to call this JSON in my JavaScript code and asign it a variable ?
var newSelling = data from the JSON
The JSON is being generated by another system which generates it that way so I need to read the JSON to get the data needed for other processes
the JSON is automatically generated and it is in an external file

So it is a JSON file. Request it with fetch or XMLHttpRequest and access the JSON.
fetch('/path/to/your/file.json')
.then(response => response.json())
.then(data => {
console.log(data)
});

If you want to read the file in the Browser from your local you can use one of these solutions :
Fetch API.
Axios.
XMLHttpRequest.
I recommend Fetch API.
fetch("data.json")
.then(response => response.json())
.then(json => console.log(json));
It works in Firefox, but in Chrome you have to customize security setting.

If you look carefully, you'll see that this JSON file is just a JSON array with only one Object inside of it. So you have to access the object that is in the array.
let arr = JSON.parse(*the json object*);
let obj = arr[0];
I haven't tested this, but hopefully this helps.

Here in your case, using JSON.parse only is not working
but the combination of JSON.stringify and JSON.parse is working as I tried.
So first, we can stringify it and then we can parse it
Like this :
var a = [
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
];
var b = JSON.stringify(a);
var c = JSON.parse(b);
console.log(c[0].id); //output : 1

Parsing JSON should work as follows:
const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: true
More info
Edit:
You can red this question. I think it may help

Related

How can I insert data from a JSON to a const variable in NodeJS for using an API?

I'm currently working on a NodeJS project, this takes data from a JSON and then use it to take weather stuff form an API, after that I want to save it to a DB, I already asked about it and that question helped me fixing some problems but now I have some others, I'm sending the data to a constant but the issue is that I don't know why am I getting an error in the JSON Parse, I want to use the lat and lon from the JSON (I have like a hundred data coords) and insert it into the const, any help would help, This is the error I'm getting
Successful connection
[]
undefined:1
^
SyntaxError: Unexpected token in JSON at position 0
at JSON.parse (<anonymous>)
here is my function that takes data from JSON and gets data from the API:
async function calcWeather() {
fs.readFile("./json/data.json","utf8", function (err, data) {
if(err) throw err;
data2 = JSON.parse(data);
console.log(typeof data2);
for (let item of data2) {
let base = `https://api.openweathermap.org/data/2.5/weather?lat=${item.latjson}&lon=${item.lonjson}&appid=${api_key}&units=metric&lang=sp`;
fetch(base)
.then((responses) => {
return responses.json();
})
.then((data) => {
var myObject = {
Id_Oficina: item.IdOficina,
Humedad: data.main.humidity,
Nubes: data.clouds.all,
Sensacion: data.main.feels_like,
Temperatura: data.main.temp,
Descripcion: data.weather.description,
};
// validation and saving data to array
if (myObject.Temperatura < 99) {
lstValid.push(myObject);
}
});
}
});
console.log(lstValid);
}
here is the JSON where I take the data:
[
{
"latjson": 1,
"lonjson": 1,
"IdOficina": "1"
},
{
"latjson": 2,
"lonjson": 2,
"IdOficina": "2"
}
]
I think the issue is in the parse, but I don't get what I am doing wrong
Since you are reading the file with fs.readFile, you are getting a string and not a JavaScript object. You would need to parse it entirely in order to be able to manipulate the content (you seem to be parsing the first character only):
const fs = require('fs')
let rawdata = fs.readFileSync('./data.json')
let data = JSON.parse(rawdata)
Personally, I think it's way easier to require it (no need to use fs):
const jsonData = require('./json/data.json')
async function calcWeather() {
for (let item of jsonData) {
// ...
}
}

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 import a json file in Chrome?

My file data.json contains a json object like:
{ "k": : "..some object...", "a": [ "...", "bbb" ] }
In Node I am able to do:
let data = require("./data.json");
and get the whole object in the json file into the variable data.
How do I achieve the same in the Chrome browser?
Assuming you are fetching the json file from the server:
fetch(urlOfJsonFile)
.then(function(response)
{
return response.json();
})
.then(function(data)
{
//Use data as javascript object
})

Why is my JSON fetch query returning undefined values?

I am trying to find some specific data from a JSON file using the fetch query, my code so far looks like this:
function newfuntion() {
var my_list = []
fetch("url")
.then(res => res.json())
.then(data => {
x= data.mydata.filter(el => el.Process==="process1")
myvar = x.Shortnum
console.log(myvar)
})
}
My issue is where I define myvar as shortnum, it cannot narrow down the query to only Shortnum.
If I run this without the .shortnum filter it works fine. i.e. console.log(x) will return the dictionary where the process is process1.
Here is a sample of the JSON file:
{
"mydata": [
{
"Process": "process1",
"Shortnum": "00000",
"Status": 1,
}
]
}
filter returns an array. What you want is probably the first (only?) matching object.
You might use find instead:
let x = data.mydata.find(el => el.Process==="process1")
let myvar = x.Shortnum
console.log(myvar)

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

Categories

Resources