How read JSON nested from Angular JS $http service? - javascript

This is my main JSON file
{
"chartType" : ["column", "column", "pie"],
"chartTitle": ["Cantidad de equipos", "Cantidad de artículos consumibles","Cantidad de empleados a cargo"],
"yAxisTitle": ["Equipos", "Consumibles", "Empleados"],
"seriesName": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"],
"seriesData": ["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
}
That loads others PHP JSON_ENCODE files in "seriesName" and "seriesData".
These JSON results generate keys "id" and "nombre" (spanish word for name).
How read values for these keys through Angular Service $http.get of the main JSON?
**UPDATE (06/03/2016)**
I'm middle of road!
I read the JSON objects from "seriesName" array with angular.fromJson function as follow:
var deserialize = angular.FromJson(data);
var objects = deserialize.seriesName;
console.log(objects);
That's throws me an array of objects:
["conexion_equipos_basededatos_json.php", "conexion_consumibles_basededatos_json.php", "conexion_basededatos_json.php"]
Thus, how I could read the objects contained in these URL's through Angular?

First of all you need to decode the JSON in PHP using json_decode(), then you treat the result as an object.
Try something like;
$data = xyz; // pass in the JSON object
$res = json_decode($data); // decode JSON
$chartType = $res->chartType; // access property as an object
You can also try var_dump($res) to get a clearer understanding of the structure and how to access it;

You can do following.
$http.get('url_to_json').then(fucntion(response) {
var myJson = response.data;
var keys = Object.keys(myJson);
console.log('Your keys', keys);
}, fucntion(error) {
});

Altough have button, I could resolve this issue.
I have created a repository that integrates Angular.js, PHP, and Highcharts, with Materialize.css, adding series dynamically from external JSON.
link: https://github.com/Nullises/DynamicSeriesHighchartsAngular

Related

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

load JSON with JQuery

Is it possible to load JSON file once, and in further call will use loaded JSON (for ex. from cache)?
The easiest way to achieve this is to use the localStorage of JavaScript.
Let's assume you have an object named object.
You can store it this way:
// parse Object to JSON, then store it.
let jsonObject = JSON.stringify(object);
localStorage.setItem('myObject', jsonObject);
And if you want to use it again, do it this way:
// load it from storage and parse the JSON to Object.
let jsonObject = localStorage.getItem('myObject');
let object = null;
if(jsonObject){
object = JSON.parse(jsonObject);
}
Then change it according to your needs and store it again.
You can delete it by
localStorage.removeItem('myObject');
There are so many ways,
You can store your JSON file in assets folder and read them like this - https://stackoverflow.com/a/19945484/713778
You can store it in res/raw folder and read the same as show here - https://stackoverflow.com/a/6349913/713778
For basic JSON parsing, Android's in-built JSONObject should work - https://developer.android.com/reference/org/json/JSONObject.html
For more advanced JSON parsing (json-java mapping), you can look at GSON library - https://code.google.com/p/google-gson/

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

append data to a JS "JSON array"

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.

Constructing a valid JSON object with Javascript

I'm using the code below to construct a JSON object that looks like this:
{"contacts":[{"provider":"Yahoo","firstName":"myname","lastName":"surname","nickname":"mynick","email":"myemail#hotmail.com","photoURL":"http://l.yimg.com/dh/ap/social/profile/profile_bxx.png"}]};
var data = {};
var contacts;
var gc = $.when(gigya.socialize.getContacts({callback: function(response){
data['contacts'] = response.contacts.asArray();
}}));
gc.done(function(response) {
contacts = data;
});
console.log(contacts);
When I pass the resulting contacts object to Google soy template, the JSON object doesn't seem well constructed.
With the code above, how do I construct a valid JSON object?
Thanks for helping out.
The object seems ok,
try using JOSN.stringify() example jsFiddle
or JSON.parse()
You can see in example, you can turn object into valid JSON and reverse into valid JS object.
Regarding your code
What do you get from response ?
And why do you use response here if you do not make use of it?
gc.done(function(response) {
contacts = data;
});
I would change this line EDITED
data['contacts'] = response.contacts.asArray();
to
contacts = JSON.parse(response.contacts);
and remove
gc.done(function(response) {
contacts = data;
});

Categories

Resources