How to make a JSON object? - javascript

I want to create the following JSON object, as seen from a console log:
Object
. member: Object
. id: 8286
I've been trying:
'member' :[{'id': 8286}]
but get the following error: "Uncaught SyntaxError: Unexpected token :"
What am I doing wrong? Thanks

var member = {
id: 8286
};
this allows you to access it like
member.id
You could have also meant something like:
var data = {
member: {
id: 8286
}
};
which you would access like so:
data.member.id
If this is not what you want, please clarify in your post cause I'm not sure I'm following your request correctly.

You're missing the curly braces surrounding the object.
As in:
var x = {'member': [{'id':8286}]};

You mean something like this?
{
"member": {},
"id": 8286
}

{
"member":{
"id":value
},
{
another_data:value
}
}
the data are accesses using the(.) operator.
the id is accessed by member.id

Related

make the query dynamically to change using sanity.io groq

Hi there I'm trying to make a post request where I want to update one field on sanity.io
this is my query
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
`rewardItem[_key == \"${key}\"].lastTimeReward`: "TEst",
},
}
but this won't let me even run my project,
its giving me this error on console.log: Unexpected token;
When I do my query like this, it works
patch: {
id: "f6c46b53-9313-4354-a4d6-7a40b06ee4c0",
set: {
"rewardItem[_key == \"e88959e43ce7\"].lastTimeReward": "Test",
},
}
}]
Thanks a lot.
Your set-property is an object, and you can't enter a dynamic key directly into the object. To do what you are trying to do here, you can wrap the dynamic key in square brackets like this. That should give you the output you desire
const variable = "example"
const a = { [`template ${variable}`]: "value" }
console.log(a)

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.

How can I accesss to the elements of array objects?

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

Replacing items in JSON using Javascript

I am new to javascript. I am trying to replace a JSON elements with a set values passed from another function. When i parse the object I am getting an error message unexpected token at pos 0.
Thank you.
var defaultMessage = {
"MTI": "1101",
dataElements: {
"DE01": "101",
"DE02": "201",
"DE03": "301",
"DE04": "401",
"DE05": "501",
"DE06": "601",
"DE07": "701"
}
}
replaceDefaultElements: (testElements) => {
console.info(testElements)
console.info(defaultMessage);
var messageElements = JSON.parse(defaultMessage.dataElements);
Object.keys(testElements).forEach(function (key) {
messageElements[key] = testElements[key];
});
return messageElements;
}
//Calling from JEST test function:
test('Should be ', () => {
expect(functions.replaceDefaultElements('{"MTI":"1101",{"DE01":"XXX"}}')).toEqual({
"MTI": "1101",
dataElements: {
"DE01": "XXX",
"DE02": "201",
"DE03": "301",
"DE04": "401",
"DE05": "501",
"DE06": "601",
"DE07": "701"
}
})
When i parse the object I am getting an error message unexpected token at pos 0.
defaultMessage.dataElements is a JavaScript object. It isn't JSON.
Don't use JSON.parse there.
testElements, on the other hand, is JSON.
Replace JSON.parse(defaultMessage.dataElements) with defaultMessage.dataElements
Replace Object.keys(testElements) with Object.keys(JSON.parse(testElements))
Hope it will work

Console.log of function returning object

So I have a function which is returning an object which has an object as value. I need to console.log the result of the function, however what I get is this:
testedDatalayer: {
event: 'mkt_pageInformation',
eventDetails: { page: [Object], pagePath: '/' }
}
I need to display the value as normal instead of [Object]. I know I can stringify it, however I really want to keep it as an object rather then string and make it look like this:
expectedDataLayer: {
event: 'mkt_pageInformation',
page: { type: 'xxx', category: 'xxxx' },
pagePath: 'xxxxx'
},
Is there any way of keeping that structure and console logging the function without the need of strinfigy?
EDIT: doing it on node.js and logging to cmd
You can try console.dir() instead of console.log()
If you're using Node, you could try using util.inspect:
const inspect = require('util').inspect;
console.log(inspect(yourObject,{depth: Infinity}));
For more info you could check the nodejs docs for it at:
https://nodejs.org/api/util.html#util_util_inspect_object_options
You can format it as an object structure using JSON.stringify() third parameter to pretty print Object.
var objectToLog = {
expectedDataLayer: {
event: 'mkt_pageInformation',
details: { page: { type: 'xxx', category: 'xxxx' } },
pagePath: 'xxxxx'
}
}
console.log(JSON.stringify(objectToLog,null,4));

Categories

Resources