Reading a json response with multiple objects in javascript - javascript

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

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 retrieve specific value from list of Json Object in NodeJS

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

Parsing a JSON Stringified variable returns the value undefined?

The code below is the entirety of my discord.js message event, I am using discord.js as well as node-wit. When wit identifies a message including a math expression, it will evaluate the value and send it back to the user.
It sends back data using JSON.stringify(). However when I try and parse it, everything I log only returns undefined.
client.on('message', (message) => {
wClient
.message(message.content, {})
.then((data) => {
const response = JSON.stringify(data, ['intents', 'name', 'confidence']);
const responseParsed = JSON.parse(response);
console.log(response);
console.log(responseParsed);
if (responseParsed.name == 'Math') {
message.channel.send(eval(data));
}
})
.catch(console.error);
});
The actual response of the console logs for the JSON.stringify() and then the JSON.parse() are listed below:
JSON.Stringify()
{"intents":[{"name":"Math","confidence":0.9945}]}
JSON.parse()
{ intents: [ { name: 'Math', confidence: 0.9945 } ] }
based on this structure
{ intents: [ { name: 'Math', confidence: 0.9945 } ] }
I assume that this is how it should be
to try
if (responseParsed.intents[0].name == 'Math') {
message.channel.send(eval(data));
}

passing in json variable into sendgrid's dynamic_template_data

I'm having some trouble passing into a variable that holds a json object into sendgrid's dynamic_template_data. My setup looks like this:
const send = async (address, mentions) => {
console.log('mentions json obj', mentions)
let name = "john"
try {
let config = {
headers: {
Authorization: `Bearer ${process.env.sendgridKey}`,
}
}
let data = {
personalizations: [
{
to: [
{
email: `${address}`,
},
],
dynamic_template_data: {
name: name,
allMentions: mentions
}
}
],
from: {
email: "email#email.com",
name: "Mentionscrawler Team"
},
template_id: process.env.template_id,
}
await axios.post("https://api.sendgrid.com/v3/mail/send", data, config)
} catch (error) {
console.error(error, 'failing here>>>>>>>')
}
}
when I console.log mentions, which is json, and paste the code I get from the terminal directly into the allMentions key, it works. but when I just pass in mentions itself, nothing shows up on the sent email. I've been very confused the last few hours why this is happening. Any advice appreciated.
edit: i should also note that allmentions is an object with keys that hold arrays. So I'm looking to iterate over those arrays. Again, this totally all works if I just paste in directly what mentions is, but passing in mentions is giving me an issue.
Thank you very much,
just realized what was wrong. sendgrid's template requires a json object, so I assumed that I needed to use json.stringify on my mentions obj. Turns out I didn't need to do that, as long as all values are in string format.

Manipulate ajax response

I have a ajax post method. I get an object from the backend
$.ajax({
type: "POST",
url: URL_one,
data: submitData
}).then(function (response) {
console.log("Ajax response", response);
});
and when i do a console.log(response); inside the post method, i see the following data.
>Object{Info:Array[200]}
>Info:Array[200]
>[0-99]
>0:Object
name:'Ashley'
on_pay: true
valid:"0"
>[100-199]
So each array has objects like one mentioned above with name, on_pay and valid. I want to do the following
Since all on_pay values are true in my case, i need to convert it to false. Also valid has string of 0. I need to put all values as blank instead of 0.
Is it possible to do ?? Can someone please shed some light on these.
Considering the JSON structure that you show, following should work to change the on_pay value:
response.Info.forEach(function(item){
item.on_pay = false;
});
If I'm understanding your question correctly, response is an array of items. You want to keep those items intact, but turn the on_pay property false and valid to an empty string.
You can use Array::map() to transform each item.
/*jslint node:true*/
"use strict";
// I am assuming your response looks something like this
var response = {
Info: [
{
name: "Ashley",
on_pay: true,
valid: "0"
},
{
name: "Jim",
on_pay: true,
valid: "0"
},
{
name: "John",
on_pay: true,
valid: "0"
}
]
};
// This will produce a new variable that will hold the transformed Info array
var fixedResponseInfo = response.Info.map(function (item) {
item.on_pay = false;
item.valid = "";
return item;
});
// This will edit the response.Info array in place
response.Info.forEach(function (item) {
item.on_pay = false;
item.valid = "";
});
console.log(fixedResponseInfo);
console.log(response);
This will keep your original response variable and produce a new variable fixedResponseInfo that contains the transformed array. If you don't care whether data in response is changed, you can use Array::forEach() to iterate instead.

Categories

Resources