Parsing JSON under Array object - javascript

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

Related

Storing and retrieving JSON in angular4

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

How could I parse this json-string?

I have a string:
[{"data1":"A"},{"data2":"B"},{"data3":"C"}]
I used jQuery to convert this string to json:
test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
I got 3 objects:
I don't know, how could i get the key and value in this string-json?
Or the format of string-json is wrong?
have you tried cycle thorough the parsed array?
var test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
for(var a=0;a<test_json.length;a++) {
var obj = test_json[a];
for(var idx in obj) {
console.log(idx, obj[idx]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
It has parsed the JSON correctly and returned an array of objects. You could do the following to access the first item containing { data1: "A" }:
console.log(tessst[0])

javascript convert string to data

I have JavaScript code below.
var data = "[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]";
I need convert the string to an data by delete the "" surrounding the array stored as "data" in JavaScript so after convert it suppose like below:
var data = [{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}];
How to make the convert?
To convert a JSON object to Javascript object use:
var data = '[{"PR_ID":23096,"P_ID":23014},{"PR_ID":33232,"P_ID":23014},{"PR_ID":33308,"P_ID":23014},{"PR_ID":33309,"P_ID":23014}]';
JSON.parse(data);
But first change the double quote to single quote, otherwise the JSON object wont be a valid JSON.
After this you can walk the array in the following way:
var jsonParsed = JSON.parse(data);
for(var val in jsonParsed) {
if(jsonParsed.hasOwnProperty(val)) {
// do something with the values
}
}

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

Simple way to import and export and store Arrays

For example I have something like this.
var Ar : Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
And I need to store it in simple text file. Like this
ArText : String ;
ArtText = "0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
You got the point.
What is best way to convert Array in to a readable string, and then back? Javascript code will be best, but you can use almost any similiar.
My initial impulse was to convert it directly to JSON, but then I realised that JSON.stringify() would return something like this:
["apple",null,null,"pineapple",null,null,null,null,null,null,null,null,"car",null,null,null,null,null,null,null,null,"apple",null,null,null,null,null,null,null,null,null,null,null,"dog",null,null,null,null,null,null,null,"cat"]
Because your array has a bunch of undefined slots that all become null because JSON doesn't support undefined values. Which would be OK if you just need to store it except then when you convert it back to an array you'd end up with nulls everywhere instead of undefined so you'd have to allow for that (not a big deal) but in any case it sounds like you want it to be human-readable too.
So instead I suggest you convert it to an object and then convert the object to JSON using JSON.stringify(). To convert it back you use JSON.parse() to turn your string into an object, then loop through the object properties to create a sparse array.
What I'm proposing would result in a JSON string like this:
{"0":"apple","3":"pineapple","12":"car","21":"apple","33":"dog","41":"cat"}
The code:
function sparseArrayStringify(arr) {
var obj = {},
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
obj[i] = arr[i];
return JSON.stringify(obj);
}
function parseToSparseArray(str) {
var arr = [],
obj = JSON.parse(str),
k;
for (k in obj)
arr[k] = obj[k];
return arr;
}
var stringifiedArray = sparseArrayStringify(Ar); // where Ar is your array
// and change it back
var anArray = parseToSparseArray(stringifiedArray);
Working demo: http://jsfiddle.net/XXqVD/
Note: in my parseToSparseArray() function I didn't bother testing that the properties of the object in the string being parsed actually are non-negative integers, but you can add that if desired.
Newer browsers support the JSON object with associated methods, or for older browsers you can include the json2.js library.
By the way, the code in your question is invalid JavaScript: you can't declare variables with a type in JS. See the examples in my code for how to declare arrays, objects, etc.
EDIT: OK, I don't know why on earth you'd want the non-JSON version when JSON is a well known standard format, but here are some untested functions that read and write exactly the format from the question:
"0-Apple,3-pineapple,12-car,33-dog,41-cat,21-apple"
Note that your proposed format won't work if any of the array elements contain commas or hyphens. Which is why JSON is the way you should go. Anyway:
function serialiseArray(arr) {
var workingArray = [],
i;
for (i=0; i < arr.length; i++)
if (typeof arr[i] != "undefined")
workingArray.push(i + "-" + arr[i]);
return workingArray.join(",");
}
function deserialiseArray(str) {
var arr = [],
items = str.split(","),
item,
i;
for (i=0; i < items.length; i++) {
item = items[i].split("-");
arr[item[0]] = item[1];
}
return arr;
}
If it's just strings in the array, you could use the join() method on the Array object to create a comma separated string, and then use the split() method on the String object to convert the string back to an array.
var Ar = new Array;
Ar[0] = 'apple';
Ar[3] = 'pineapple';
Ar[12] = 'car';
Ar[33] = 'dog';
Ar[41] = 'cat';
Ar[21] = 'apple';
var stringRepresentation = Ar.join(",");
var backToArray = stringRepresentation.split(";");
You can see this working here; http://jsfiddle.net/ykQRX/. Note I've also fixed your invalid JavaScript (var Ar = new Array;).

Categories

Resources