Reading json file in node.js - json

This must be something really silly. After spending the last few hours, I am here for help.
I have a users.json file
{
"Test_Session": {
"test_SessionID": [
{
"$": {
"id": "1"
},
"test_type": [
"1"
],
"Test_IDtest": [
"1"
],
"DataURL": [
"data1"
]
}
]
}
}
I try to read DataURL by
var jsonData = require('./users.json');
var test = JSON.stringify(jsonData)
console.log(test.Test_Session.test_SessionID.DataURL);
In console, I get "Can't read property test_SessionID of undefined".
What's going on?

Your main issue is that test_SessionID is an array, so when you try to access DataUrl, it will be undefined. You need to select the index of the test_SessionID object you want to read from. Try this:
console.log(test.Test_Session.test_SessionID[0].DataURL);
Also, you don't need to JSON.stringify anything, Node automatically reads the file in as JSON, so just doing
var jsonData = require('./users.json');
console.log(jsonData.Test_Session.test_SessionID[0].DataURL);
should work fine.

Node is already interpreting the JSON, try the following:
var test = require('./users.json');
console.log(test.Test_Session.test_SessionID[0].DataURL);

Related

How add terraform variables in a JSON file

Hey team I’m having trouble finding in the documentation on how to add terraform variables in a JSON file,
I need inject this variable in this JSON,
In this JSON of this shape but not it works,
I did try with var and locals, I tried it with var and locals, but it does not work, it is by default
You could use templatefile function [1]:
locals {
mystring = "Test"
}
resource "grafana_dashboard" "metrics" {
config_json = templatefile("${path.root}/EC2.json.tpl", {
mystring = local.mystring
})
}
For this to work, you would have to change the JSON to be:
"datasource": {
"type": "CloudWatch"
"uid": "${mystring}"
}
The file with JSON data should also be renamed to EC2.json.tpl.
[1] https://www.terraform.io/language/functions/templatefile

Getting "variable is undefined" or "variable.map" is not a function while trying to fetch data from JSON response

I have done this before, but I am not sure what error I am making here in order to populate the select drop down with options retrieved from JSON response. The API call is successfull and I can see the data pulled but not able to display it in options of select drop down.
varibale in concern is idsFetched
let idsFetched = this.state.storeRanges.Stores
console.log("ranges I/O ", idsFetched);
let options3 = idsFetched.map(store => {
return {value: store.value.description, label: store.value.description};
})
---- JSON RESPONSE ---- Stored in variable = storeRanges
{
"Stores": [
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-123",
}
},
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-456",
}
},
{
"mode": "LOADED",
"value": {
"description": "Ontario-Example-789",
}
},
]
}
First make sure you have done JSON.parse(apiResponse) otherwise you'll just be storing a string, making storeRanges.Stores === undefined probably causing your issue.
Secondly, make sure the State has been set first, by wrapping the function in a check. If you've done it correctly the re-render after setting state should fire it off no worries
I was able to fix the issue by declaring an empty variable in state and then updating the state in ComponentDidUpdate hook and accessing that in onChange method.
componentDidUpdate(prevProp, prevState){
this.setState({idsFetched: this.state.storeRanges.Stores})
}
onChange(){
options = ranges.map(range => {
return {value: range.value.description, label: range.value.description};
})
}
This is how I could access the array of stores fetched from JSON response!
Thank you everyone for looking into my query!

Dynamic JSON structure

I am trying to make a JSON-key dynamic with the following data and function:
var jsonData = [ ];
addProcess("Text1", "Text2", jsonData)
function addProcessingPurpose(title, domain, arr) {
arr.push({
"First": title,
domain : {
"subitem": {
"Subsubitem": "text"
}
}
});
}
I get the desired output expect I don't seem to manage setting the keys dynamically from the function parameter. E.g. now it prints "domain" instead of "Text2" which is my desired output. How can this be solved please?
Sorry for the stupid question, solved it myself didn't saw I forgot the [ ] around the key.. Thank you anyway, maybe it can help someone else..

using JSON file to define array values in Node.js

In node.js my program app.js, i am defining array like this
var myList = [["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]];
console.log (myList)
It is giving output but i want an external JSON file to supply the parameter of myList array instead of me defining it hardcore
i have prepared a JSON file named ppm.json and change my code to
var myList = JSON.parse(fs.readFileSync('ppm.json', 'utf8'));
console.log (myList[1])
my ppm.json is this
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}
it giving me output as undefined in console. what is the problem. pls help.
Without more requirements it's hard to give a definitive answer, but one thing you can do:
app.js
var myList = require('./my_list.json');
console.log(myList);
my_list.json
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
You can use require() to load both JSON and JavaScript files.
For example,
myFile.json:
[["SAHRUKH",47.49,"HIT"],["SALMAN",47.3,"FLOP"]]
app.js:
var myList = require( './myFile.json' );
console.log (myList)
You're accessing your item wrong. You don't have an array you have an object.
Access your heros age like this:
myList['age']
You might also consider changing your file to look like this:
{
"SAHRUKH" : {
"age" : "47.49",
"lastpict" : "HIT"
}
}
In which case you'd get your hero's age like:
myList.SAHRUKH.age;
//Or Equivalently
myList['SAHRUKH']['age']; //The dot notation above is preferred though!
Or this
{ "heros" : [
{
"name" : "SAHRUKH",
"age" : "47.49",
"lastpict" : "HIT"
}
]}
In which case you'd get at age like:
myList.heros[0].age;
If you adjust your ppm.json file to look like:
[{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
}]
It should drop in and work directly. If you wanted to include multiple heroes, it would look like:
[
{
"hero": "SAHRUKH",
"age": "47.49",
"lastpict": "HIT"
},
{
"hero": "SALMAN",
"age": "47.3",
"lastpict": "FLOP"
}
]
Your resulting myList should be an array in the example you provided, with entry 0 being the first hero object (SAHRUKH) and 1 being the second, and so on.

Google Apps Script and Big Query - tabledate.insertAll

Have been struggling with this..... Google Apps Script and the Big Query API are working well however when I try to use BigQuery.Tabledata.insertAll I keep getting an error saying 'no such field'.
When I try to run the same thing through the Google API explorer it works fine. The documentation says the command is :
BigQuery.TableData.insertAll(TableDataInsertAllRequest resource, String projectId, String datasetId, String tableId)
I have constructed the TableDataInsertAllRequest resource as per the documentation https://developers.google.com/bigquery/docs/reference/v2/tabledata/insertAll and it looks like this :
{
"kind": "bigquery#tableDataInsertAllRequest",
"rows":
[
{
"json":
{
"domain": "test",
"kind": "another test"
}
}
]
}
This matches my table schema.
When I run the command the error returned is :
{
"insertErrors": [
{
"index": 0,
"errors": [
{
"message": "no such field",
"reason": "invalid"
}
]
}
],
"kind": "bigquery#tableDataInsertAllResponse"
}
As I say the same TableDataInsertAllRequest resource works fine in the API explorer (clicking Try It on the documentation page above) it just does not work through Apps Script.
Any help gratefully received.
I've run into this too, and had somewhat better luck with this variation.
var rowObjects = [];
// Generally you'd do this next bit in a loop
var rowData = {};
rowData.domain = 'test';
rowData.kind = 'another test';
rowObjects.push(rowData);
// And at this point you'd have an array rowObjects with a bunch of objects
var response = BigQuery.Tabledata.insertAll({'rows': rowObjects}, projectId, datasetId, tableId);
Some things to note:
I don't indicate a kind -- it is implied by the call to insertAll()
I use dot notation (is that the right term?) rather than strings to stuff attributes into my "row objects"
I'm not sure which of these is the Secret Sauce. Anyways, in the end, the structure of the call looks about like this:
BigQuery.Tabledata.insertAll({'rows' : [
{
'domain' : 'test',
'kind' : 'another test'
}
]
},
projectId,
datasetId,
tableId);