append data to a JS "JSON array" - javascript

In JS (it is node/js but actually is a general JS question)
I have a data object which is a result of JSON coming from the server.
I want to manipulate the data before passing it to the view.
How can I do that? (I can make additional objects that contain the rest of the data but it feels wrong and un-natural)
var response = JSON.parse(moment_respose_content );
if (response.success)
{
var data = response.data[0];
//add additional fields to data
}

This may have already been answered
A JSON object is just a JS object, you can add/edit/remove parts like you would any other.

Related

How to append an item to a JSON stored in a file?

Im triying to write a JSON object to a DB with FS but it´s not working as expected. What i want to do is write the JSON data inside this: [] Example:
[
{"name":"jhon"},
{"name":"jhonathan"}
]
Here is the code:
Thanks.
The comment you provided doesn't make much sense, because the JSON data you provided in the post and in the comments is completely different. But I get the gist of it. I guess you have a JSON file containing an array and you want to push new items to it. Let's do this.
The thing is, when you call fs.appendFile, you're only writing to the end of the file. You're not following JSON format by doing so.
You need to do this:
Read file content.
Parse JSON text into an object.
Update the object in memory.
Write object in JSON format back to the file system.
I'll call the synchronous methods for simplicity's sake, but you should be able to convert it to async quite easily.
const path = __dirname + 'db.json'
// Reading items from the file system
const jsonData = fs.readFileSync(path)
const items = JSON.parse(jsonData)
// Add new item to the item list
items.push(newItem)
// Writing back to the file system
const newJsonString = JSON.stringify(items)
fs.writeFileSync(path, newJsonString)

How can I convert an SQL primary key in JSON to a javascript object key with the other data as it's value

Whenever I read all my data from a database table and receive it as JSON from my API, I get my data like this (unique_name being the primary key in this example):
[{"unique_name":"alice", "age":18, "city":"kansas"},{"unique_name":"bob", "age":20, "city":"chicago"}]
In my javascript application, however, I need my data to be formatted like so:
const myData = {alice: {age:18, city:"kansas"}, bob: {age:20, city:"chicago"}}
I guess this could be done with object mapping of some sort, but I'm afraid this would be too slow with a lot of entries. Is there any clean way to do this?
There is no real problem to map a lot of entries.
If you want more performences you should do it server side (eg: on a nodejs server)
You can simply use a .forEach()
Exemple (not complete so you just get the idea)
const myData = {};
mySQL.forEach(entry => myData[entry.unique_key] = entry)

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

object has no method push in node js

I am trying to append the user details from the registration form to the json file so that the user-details can be used for authentication. the problem is i am not able append to the json file in correct format.The code i have tried so far is,
var filename= "./user_login.json";
var contents = fs.readFileSync(filename);
var jsonContent = JSON.parse(contents);
//sample data
var data =[
{
"try" : "till success"
}
];
jsonContent.push(data);
fs.writeFileSync(filename,jsonContent);
I have tried different methods that i found by googling and nothing worked so far. I want the data to be stored in correct format. Most of the times i got this error like object has no push function. So what is the alternative to that?
The correct format i am looking for is ,
[
user1-details : {
//user1 details
},
user2-deatils : {
}//So on
]
Object has no push function, arrays do. Your json is invalid too, it should be an array:
[ // here
{
//user1 details
},
{
//So on
}
] // and here
Now, you can use push(). However, data is an array, if you want an array of objects in your json file, it should be a simple object:
var data = {
"try" : "till success"
};
You also have to stringify the object before writing it back to the file:
fs.writeFileSync(filename, JSON.stringify(jsonContent));
You should consider using something like node-json-db, it will take care of reading/writing the file(s) and it gives you helper functions (save(), push()...).

Script works in development environment, but not in production

I am running an angular app. I am having the strangest effect ever...
I am calling a backend which returns a json. I parse that json and build an object structure client side. It works perfectly in dev but the exact same code does provide strange effects on prod. See code inline comments for hints. The only thing I could think of is that the data comes different from prod...
I can't see what's wrong, as it's the exact same code, and it's driving me completely nuts, probably the worse thing I ever saw in 10+ years programming!
Basically the json structure is a list of objects, every object has a reference ID, and several objects are correlated by the same reference ID - I need a structure where I'd access all objects with the same reference ID.
Maybe I'll make a fool of myself here but I really can't see it...I just ran the data in two JSON validators and both say the data is valid.
app.factory('ItemService', ['ItemProvider', function(itemProvider) {
var itemSrv;
var obj_by_id = {}; //create empty object
itemSrv = function(callback) {
itemProvider.get_data()
.success(function(data) { // callback ok, data has json content
for (var i=0; i<data.length; i++) {
obj = data[i]; // I get the object in the json
if (! (obj.identificador in obj_by_id)) {
obj_by_id[obj.identificador] = {}; //build a key in the object if not already available
}
obj_by_id[obj.identificador][obj.campo_nombre] = obj; //assign the object by keys
console.log(obj_by_id); **//HERE obj_by_id is ALWAYS EMPTY!!!! BUT ONLY ON PROD!!! On dev works fine...**
}
callback(obj_by_id); //Here I would get the whole structure, but it's empty on prod...
})
.error(function(data) {
console.log("Error getting data from server");
});
}
//factory function body that constructs shinyNewServiceInstance
return itemSrv;
}]);
EDIT: console.log(data) right after success, on request
dev:
http://imgur.com/10aQsx2,rJJw2bb#0
prod:
http://imgur.com/10aQsx2,rJJw2bb#1
EDIT2: you can have a look at the returned data here (will remove this link later!): http://bibliolabs.cc/milfs/api.php/ison?id=2
I am concerned about all those \u unicode chars, could that be an issue?

Categories

Resources