I have some data from an object from an S3 Bucket via Amplify.
export function amplify() {
let key = "68a92d44-f25a-4bd8-9543-cc95369ae9a0";
return Storage.get(key + ".json", {
download: true
})
.then(function(result) {
return result;
})
.catch(err => console.log(err));
}
And the resulting data looks like this:
Object { LastModified: Date Tue Nov 12 2019, ETag: "\"(lotsofnumbers)\"", ContentType: "application/json", Metadata: {}, Body: Uint8Array(4168) }
How would I go about getting the JSON data from this object?
I have tried result.Body.toString() which gives me the JSON file and its content, but I cannot write result.Body.toString().name or .meta (the content in my jsonfile), for example, it gives me "undefined". I have also tried to convert the Uint8Array to JSON with parse, whereas I get this error: "JSON.parse: unexpected character at line 1 column 1 of the JSON data".
This worked for me, don't know what was wrong, but now it works :)
var obj = amplify();
obj.then(async function(result) {
var json = await new Response(result.Body).json();
console.log(json.meta);
});
Related
I wrote a code where I am copying a one json file into another json file so my code look like this
function userData(){
fs.copyFile(
path.join(process.cwd(), "user/access.json"),
path.join(process.cwd(), "client/access.json"),
(err) => {
if (err) throw console.log(err.message);
}
);
}
so my json structure look like this
{
"Data":{
"users":[
{},
{},
{},
]
}
}
So I am reading json the copied json file like this
fs.readFile(path.join(process.cwd(), "client/access.json"), 'utf8', function(err, data){
console.log(typeof data); // showing as a string as it should shown me as object
// console.log(data.Data.users); // showing undefined
});
but the problem is the typeof of data showing me string as it should be shown as Object so I can read the data.Data.users but now I can't read this any solution whats happening here?
What you read file file is always a string. To convert it to an JSON object you need to do JSON.parse
fs.readFile(path.join(process.cwd(), "client/access.json"), 'utf8', function(err, data){
console.log(typeof data); // showing as a string as it should shown me as object
const obj = JSON.parse(data);
console.log( typeof obj);
// console.log(data.Data.users); // showing undefined
});
I use WeatherAPI's service, which returns the weather forecast given the city name
The URL looks like this https://api.weatherapi.com/v1/forecast.json?key=[API_KEY]&q=tokyo&aqi=no
After trying to paste that URL into my browser and pasting the result into a JSON beautifier, here's the result
Here's the weird part. I tried using axios to fetch the information from my app and printing it out, this is what it gave me
It was unable to fetch forecastday and instead gave me a [Object], which didn't make any sense to me since it worked just fine on my browser
Here's my code (sorry for the spaghetti formatting)
https://pastebin.com/9eJQy5Bf
I tried reinstalling the library, using proxies but the result remained the same.
forecast.forecastday is an object array, to access a property from a particular object, you have to specify the index of the object in the array.
For example if you want the date property of the first object.
const data = {
forecast: {
forecastday: [{
date: "2022-04-03"
}]
}
}
const date = data.forecast.forecastday[0].date; // index [0] = first element
console.log(date);
If you would have multiple days, you could loop over them or use a function like map() to get the specific items.
const data = {
forecast: {
forecastday: [{
date: "2022-04-03",
date_epoch: 123456789
},
{
date: "2022-04-04",
date_epoch: 123456789
}
]
}
}
const dates = data.forecast.forecastday.map(({ date }) => {
return { date }
});
console.log(dates);
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) {
// ...
}
}
I'm trying the below code to retrieve the executionArn but I'm getting this error
Error [SyntaxError]: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
How to get executionArn or stateMachineArn from each record? Any help would be much appreciated.
console.log(data) - Output
{
executions: [
{
executionArn: 'arn:aws:states:us-east-2:12222:execution:test:dcb689bc',
stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
name: 'test-name',
status: 'SUCCEEDED',
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
},
{
executionArn: 'arn:aws:states:us-east-2:12222:execution:test:sd32dsdf',
stateMachineArn: 'arn:aws:states:us-east-2:12222:stateMachine:test-sm',
name: 'test-name1',
status: 'SUCCEEDED',
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
}
],
nextToken: 'aadfdfdf'
}
Code:
stepfunctions.listExecutions(params, function(err, data) {
if (err) console.log(err, err.stack);
else
console.log(data)
//console.log(data.executions[0].executionArn)
data = JSON.parse(data);
data.forEach(function(result) {
var arnValue = result.executions.executionArn;
console.log(arnValue);
});
});
data is an object and executions inside it is an array, so try this
data.executions.foreach(function (execution) {
console.log('executionArn', execution.executionArn)
console.log('stateMachineArn', execution.stateMachineArn)
})
executions.map(e=>{
// access it here
let a = e.executionArn;
});
The provided output (data) is not a valid JSON object,
{...
startDate: 2021-06-17T13:43:39.817Z,
stopDate: 2021-06-17T13:43:53.667Z
}
For valid JSON, it should look like
{...
"startDate": "2021-06-17T13:43:39.817Z",
"stopDate": "2021-06-17T13:43:53.667Z"
}
for it to be iterated correctly.
If the data is from the server (API), stringify the dates before returning them, and the values could be found by
data.executions.map(execution=>{
let arnValue = execution.executionArn;
console.log(arnValue);
})
I have a JSON response as below.
{
returnCode: 'Success',
info: null,
result: {
payload: '{
"BatchNo":"143123",
"Supplier":"Automotive",
"ItemNumber":"AP123",
"ProdNumber":"\\"\\"",
"ItemIdentifier":"PROCURE"}
{
"BatchNo":"143123",
"Supplier":"Manufacturing",
"ItemNumber":"API124",
"ProdNumber":"PRD123",
"ItemIdentifier":"PRODUCE"}',
encode: 'UTF-8'
},
txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}
Please note, there are no arrays [{}] in the JSON data. Can someone help me how I can access result.payload.ItemNumber values and get an output like
AP123
AP124
I tried below code, but in vain. Somebody please help me
var output1 = JSON.parse(json).result.payload[1].ItemNumber;
console.log("Data:"+ output1);
Thanks.
Note
Had to clean up the payload and convert it into an array with a comma separated the list of objects. Otherwise, it is invalid response data.
Code
let json = {
returnCode: 'Success',
info: null,
result: {
payload: '[{"BatchNo":"143123","Supplier":"Automotive","ItemNumber":"AP123","ProdNumber":"\\"\\"","ItemIdentifier":"PROCURE"},{"BatchNo":"143123","Supplier":"Manufacturing","ItemNumber":"API124","ProdNumber":"PRD123","ItemIdentifier":"PRODUCE"}]',
encode: 'UTF-8'
},
txid:'8d9efd6083e6ca737e9c751baecd0c75cf738e9ce0e599bcfa26910575fa6d5f8d9efd6083e'
}
var output1 = JSON.parse(json.result.payload)[1].ItemNumber;
console.log("Data:"+ output1);