using JSON file to define array values in Node.js - json

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.

Related

handling a well-formed JSON file of an array of objects

A JSON string string passes the jsonlint test.
response = [
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"7461221587662919569"
],
}
},
"text" : "where they would 'transfer to' next.",
"lang" : "en",
}
},
{
"article" : {
"info" : {
"initial" : {
"articleIds" : [
"6613144915874808065"
],
}
},
"text" : "produto regional.",
"lang" : "pt"
}
}
]
However, after processing
require 'json'
file = File.read('/Users/main/jugg//article_samples.js')
data_hash = JSON.parse(file)
One is left with an array, whereas more frequently a hash with a name labels a subsequent array, where one works with that nomenclature such as response['data']
But in this case the array is not accessible via response[0]. How can this be considered as an array in order to process each individual element collection.each do |member|?
A curiosity: data_hash.class => NilClass
The response = ... code from article_samples.js is JavaScript, not JSON. This initializes a variable named response with a JavaScript array.
To use this as JSON, then rename the file to article_samples.json and remove response = from the file. The first line should start with [.
Now your second block of code should work just fine as long as the article_samples.json file is in the correct path.
On a side note, I suggest that you find a way to make the path more flexible. The way you have it currently hard coded is tied directly to your current machine's file system. This won't work if you want to run this code from another machine because the folder /Users/main/jugg probalby won't exist.
If this is a web server with ruby on rails, then one solution is to create an environment variable with the path where this file is stored.

Replace every array in object by first element of that array

I have a json like this:
"Client" : {
"ClientId" : "eertertwetw",
"Username" : "c.client",
"Names" : [
{
"Family" : "ClientFamilyName",
"Given" : [
"ClientGivenName"
]
}
]
}
This json is not fixed, so sometimes there are some properties and sometimes not.
I need to replace every array inside this Json with the first element of that array. So, for example, in this case it would be like
"Client" : {
"ClientId" : "eertertwetw",
"Username" : "c.client",
"Names" :
{
"Family" : "ClientFamilyName",
"Given" :
"ClientGivenName"
}
]
}
Can anyone help me to find a way to do this with Typescript?
Ok, I tried something (haven't tested it against all possible cases) but it seems like it's working.
Stackblitz - check the console for result.
let data = { Client: {...} }; // your data
data = data.map(client => {
if (!Object.hasOwnProperty(client.Names, 'Prefix')) {
client.Names.Prefix = null;
}
return client;
});
You need get the firt element in array in object.
like : Client.Names[0].Given[0].ClientGivenName

Reading json file in node.js

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

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..

Inserted Nested Item in Generated JSON in Groovy/Grails

I am using Grails 2.1 to render JSON as part of a RestFul API I created. The Domain class, based on a SqlServer table, looks like this:
String firstName
String lastName
String officialAddress1
String officalAddress2
String preferredAddress1
String preferredAddress2
(etc.). . .
Which returns JSON similar to this:
{
"firstName": "Joe",
"lastName": "Hill",
"officialAddress1": "1100 Wob Hill",
"officialAddress2": "Apt. # 3",
"preferredAddress1": "1100 Wobbly Lane.",
"preferredAddress2": "Apartment 3."
}
It is working fine but the client wants me to nest the results in this fashion:
{
"firstName": "Joe",
"lastName": "Hill",
preferredAddress {
"preferredAddress1": "1100 Wobbly Lane.",
"preferredAddress1": "Apartment 3."
},
officialAddress {
"officialAddress1": "1100 Wob Hill",
"officialAddress2": "Apt. # 3"
}
}
My question is since the domain class, and the database, are not structure in a way to return this type of nested result how can I easily change this in my returned JSON? Do I have to abandon my way of just regurgitating the JSON based on the database/domain object and do a custom converter of some kind?
i'm new to this stackoverflow thing and i hope i will not mess it but i think i know what you need. in your bootstrap.groovy file you find "def init = { servletContext -> " line
put in there something like this:
JSON.registerObjectMarshaller(YourDomainName) {
def returnArray = [:]
returnArray['firstName'] = it.firstName
returnArray['lastName'] = it.lastName
returnArray['preferredAddress'] = [it.preferredAddress1 ,it.preferredAddress2]
returnArray['officialAddress'] = [it.officialAddress1 ,it.officialAddress2]
return returnArray
}
now when you use the render with JSON as you did grails will look in bootstrap and
render the domain as you asked.
hope this helps
The posted answer was correct. I just wanted to add the slight change I made to get the exact results I needed:
Thanks! That did it. I originally that it would not work exactly how I needed it but I was wrong. I changed the syntax slightly to get the results I needed.
returnArray['preferredAddress'] = [address1: it.preferredAddress1?.trim(),
address2: it.preferredAddress2?.trim(),
address3: it.preferredAddress3?.trim(),
city: it.preferredCity,
state: it.preferredState,
postCode: it.preferredPostCode,
country: it.preferredCountry
]