Storing and retrieving JSON in angular4 - javascript

I have a scenario where there is a for loop, and in each iteration of for loop, a JSON object is obtained. Now I want to store all the obtained JSON objects in a single variable so that I can use it in other methods. Can you please provide me a way to solve this problem.

Well, this is somewhat straight-forward, only you have to parse each new bit of JSON:
var json, item, items = [];
for(var i = 0; i < number_of_items; i++) { // your loop
json = getNewPortion(); // obtained JSON (you can have whatever code that brings it)
item = JSON.parse(json); // an object corresponding to that JSON
items.push(item); // store into our array
}
This way, you'll get a variable items which is an array. If you need JSON instead, use
var finalJSON = JSON.stringify(items);

finalArray = [
{
var1: string,
var2: number
}
];
for (i = 0 ; i < n ; i++)
finalArray.push({
var1: jsonObj[i].var1,
var2: jsonObj[i].var2
});

Related

How can I change such a JSON parser?

please help me how to change such a parser to JSON for a new server response.
Old server response:
{"names":[{"name":"Oleg","act":0,"total":0},{"name":"Vitya","act":2,"total":2}]}
Old parser:
names = appData.filter( function(x) { return skipped.indexOf(x) < 0; })
get("https://serv.io/set?" + names.join("|")).then(function(data) {
result = JSON.parse(data)["names"]
for (var i = 0; i < result.length; i++) {
name = result[i]["name"]
act = result[i]["act"]
total = result[i]["total"]
}
New server response:
{"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}
As you can see in the new answer, as I understand it, there is no array and here the name is as the name of the object.
The question is how to change the old parser for the new server response.
I would be grateful for your help!
You can iterate over the keys on the object by for...in. Also destructuring assignment is useful for this kind of data processing.
const result = {"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}}
for (const key in result) {
const name = key
const {act, total} = result[key]
console.log(name, act, total)
}
Please note that for..in iteration doesn't preserve the order of elements contained in the returned JSON.
There is no guarantee that for...in will return the indexes in any particular order.
(from the for..in reference mentioned above.)
If the order of the elements is important to your system, you need to consider using another JSON parser instead of the built-in JSON.parse() method.
Simulating the new response server:
// New server response
const data = JSON.stringify({"Oleg":{"act":0,"total":0},"Vitya":{"act":2,"total":2}})
// Assuming that you have already the variables declared
let name;
let act;
let total;
// Parse the JSON and work with it
const result = JSON.parse(data)
// Save this result in a variable, to avoid use Object.entries everywhere.
const names = Object.entries(result);
// This will be your new loop
for (var i = 0; i < names.length; i++) {
name = names[i][0];
act = names[i][1].act;
total = names[i][1].total
console.log(name, act, total);
}
This will be the output every time in the loop:
Oleg 0 0
Vitya 2 2

Parsing JSON under Array object

I have a simple JSON string, encapsulated in an array created using JSONArray and JSONObject form org.json in Java.
var outObjA = [{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}];
I am trying to parse this in JavaScript. First I iterate over the array encapsulating the data using an `i" counter:
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
When I attempt to parse the JSON, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I built a try/catch into it and it returns an object:
for (var i = 0; i < outObjA.length; i++) {
var jsonData = null;
try {
jsonData = JSON.parse(outObjA[i]);
} catch (e) {
jsonData = outObjA[i];
}
console.log(jsonData);
}
Returned:
{
"LoginTime": "2018-02-14 08:51:48.0",
"User": "f00dl3",
"RemoteIP": "127.0.0.1"
}
This is valid JSON, is it not?
That's not a JSON string, it's a JavaScript array. To make it a JSON string, surround it with apostrophes, then you can parse it, and finally loop through it:
var outObjA = '[{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}]';
var outObjA = JSON.parse(outObjA);
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
Or better, you can loop through it directly without parsing:
var outObjA = [{"LoginTime": "2018-02-14 08:51:48.0", "User": "f00dl3", "RemoteIP": "127.0.0.1"}];
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
This line is not necessary.
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
Because outObjA is a array type not json,it does not need parsing simply retrieve it and display it.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned, source.
To expand further take this example from Mozilla ,
var json = '{"result":true, "count":42}';
The reason why this needs parsing is because its a string type, the JSON.parse converts that string into a JSON object, thus making it accessible. like this,
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: tru
The only way your code would work is if you did this.
var outObjA = ['{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}'];
This way the element at position zero is a string, not a JSON object.
To conclude, strings are not JSON.
JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type
(string, number, object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
you do not need parse for it is already json
you might use instead
var jsonData = outObjA[i];
console.log(jsonData['User']); // or any other key

Parse Javascript output array / Parse URL Hash

I'm trying to parse out a single value from a URL String with three varaibles, and I am currently using the code:
var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);
for (var i = 0; i < hash_array.length; i++) {
hash_key_val[i] = hash_array[i].split('=');
var array = hash_key_val[i];
console.log(array);
}
This code works to parse out the hash, but it creates separate arrays for each item and value like so:
["object1", "value1"]
["object2", "value2"]
["object3", "value3"]
By altering the array to var x = JSON.stringify(array[1]);
I can get the value which is all I need, but I only need the first value, while this code still returns:
"value1"
"value2"
"value3"
How can I alter the code so that the function only outputs value1?
Thanks!
Change the 1 for 0; Arrays start at zero index. Also I am not sure if you are aware that you are looping over the values as you are printing them out.
var arr = [
["object1", "value1"],
["object2", "value2"],
["object3", "value3"]
];
console.log(arr[0][1]);
As Arrow mentioned you need to change the index at which you access array from 1 to 0.
Additionally, why not use map:
var keys = hash_array.map(function(param){
return JSON.stringify(param.split('=')[0]);
}
with keys being ["object1", "object2", "object3"]

How to convert Javascript array to JSON string

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}
Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

JSON parsing in Javascript with no known number of items

I'm drawing a blank with the best way to process JSON data which will be of the following form:
[{"latlng":"42.6674996,-71.1786423"},
{"latlng":"53.8136722,-1.7301123"}]
var p = '[{"latlng":"42.6674996,-71.1786423"},
{"latlng":"53.8136722,-1.7301123"}]',
It will also be of variable length.
I'm having trouble looking through all the data pairs pulling off the latlng values.
I'm using the code:
for (var key in p) {
if (p.hasOwnProperty(key)) {
alert(key + " -> " + p[key]);
}
}
from this other SO question: How do I loop through or enumerate a JavaScript object?
However, the formats in the above example are different from mine.
How do I loop through each key/value in turn until the JSON string is exhausted?
I'm a little new to JSON and Javascript.
You can always use JSON.parse (on any remotely modern browser) to take a json string and get the relevant javascript structure. Once you have that, you can iterate over the structure.
So you start with
var json = '[{"latlng":"42.6674996,-71.1786423"}, {"latlng":"53.8136722,-1.7301123"}]';
and then you can get a javascript array by
var ary = JSON.parse(json);
From here you are just a hop skip and jump away from iterating over your array, getting the current element, and doing what you want.
Note for your structure, instead of returning
{"latlng":"42.6674996,-71.1786423"}
for each element in the array, you should do
{"lat":"42.6674996","long": "-71.1786423"}
that way as you iterate over the array, you can do something like
...in your for loop
var current = ary[i];
var lat = current.lat;
var long = current.long;
Use the jQuery.parseJSON - jQuery API:
var json = '[{"latlng":"42.6674996,-71.1786423"},{"latlng":"53.8136722,-1.7301123"}]';
var parsed = $.parseJSON(json);
$.each(parsed, function(index, value) {
console.log(value['latlng']);
});
or the native JSON.parse:
var json = '[{"latlng":"42.6674996,-71.1786423"},{"latlng":"53.8136722,-1.7301123"}]';
var parsed = JSON.parse(json);
var count = parsed.length;
for (var i = 0; i < length; i++)
console.log(parsed[i]['latlng']);
You're going to have to turn that string into an object before you can iterate through it safely:
var p = JSON.parse('[{"latlng":"42.6674996,-71.1786423"}, {"latlng":"53.8136722,-1.7301123"}]');
for(key = 0; key < p.length; key++) { // Start the key at zero, increment until it his the object's length
if (p.hasOwnProperty(key)) { // If the item has a key
alert(key + " -> " + p[key]); // Alert the key and then the item.
}
}
In your case, you have a multidimensional object. So each return will give you another object. How I would deal with this is by traversing the returned object like so:
alert(p[key]['latlng']);
To have a better understanding of this, look at the initial object syntax...
[
{ // key 0
"latlng": "42.68, -71.18" // key 'latlng'
},
{ // key 1
"latlng": "53.81, -1.73" // key 'latlng'
}
]
So essentially you're traversing the object using the values that the loop increments. If you have an object with 5 items your loop will grab that number and cycle through 5 times (0 .. 4). Each time it loops the incremented key variable will be used to select your item, and from there you can grab the the latlng key and return its value within the nested object.

Categories

Resources