How to read arrays in Json using JavaScript - javascript

I have a Json data as listed below:
var x = {
"array1":"['x1','x2']",
"array2":"['a1', 'a2']"
}
I need to print the individual elements of the array as below
x1
x2
a1
a2
When I do var y = JSON.parse(x), it gives me "Unexpected token o"
It seems to be coming from the JSON.parse line. If I do x = '["x1", "x2"]', there is no error but I need to have two arrays in the JSON. So how do I read them
Thanks for any answers

That is not JSON. JSON is a string and not an object hence its abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old JavaScript Object. They are different. The former is a data exchange format similar to YAML or XML while the latter is an actual object with properties and values.
Your POJO does have JSON values but since it is already an object you can't use JSON.parse to parse the entire object. That is where the "o" is coming from in the error message. JSON.parse will coerce the first argument to a string if it is not a string:
var foo = {};
JSON.parse(foo); // is essentially doing this foo.toString() which is "[object Object]"
JSON.parse('{}'); // This would parse to an empty object though since it is a string
So now when it attempts to parse "[object Object]" it sees what may be an array but then encounters a character that hasn't been quoted, the "o" in "object", and therefore throws an error.
For your example to be JSON you would need to write it as:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
document.write('<pre>' + JSON.stringify(x, null, 4) + '</pre>');
And so, now that we have a real JSON value we can answer your original question:
var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);
var vals = Object.keys(x).sort().reduce(function (arr, key) {
arr = arr.concat(x[key]);
return arr;
}, []).join('\n');
document.write('<pre>' + vals + '</pre>');

I think your JSON should be like the following
{
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}

Create your array in many different ways - two examples
var x = [{array1:['x1','x2']},{array2:['a1','a2']}]
x[1].array2 produces ["a1", "a2"]
x[1].array2[0] produces "a1"
var xx = {array1:['x1','x2'],array2:['a1','a2']}
xx.array2 produces ["a1", "a2"]
xx.array2[0] produces "a1"
third example
var xxx = {array1:{x1:'x1',x2:'x2'},array2:{a1:'a1',a2:'a2'}}
xxx.array1.x1 produces "x1"

What you have there, that 'x' variable var x = {"array1":[...]...} is already a javascript object, so you can simply pass through the object keys and display the values.
Given 'x' as the object you can have something like:
var key,
result = '';
for (key in x) {
if (x.hasOwnProperty(key)) {
result = result + x[key].join('\n') + '\n';
}
}
// There you have the result...
As John said earlier, for JSON.parse() you wold need a string as a parameter to be able to parse it into a javascript object.

so, you can use this script to do that (correct json too - http://jsonformatter.curiousconcept.com/ -, don't know why this downrate.....i guess a noob didnt realize :D):
var x = {
"array1": ["x1", "x2"],
"array2": ["a1", "a2"]
}
for (var key in x) {
if (x.hasOwnProperty(key)) {
document.getElementById("test").innerHTML += key + " -> " + x[key]+" <br>";
}
}
i've created a working fiddle here:
https://jsfiddle.net/rjzzqLmr/1/

Related

How to pass variable to JSON without printing it as String

How to pass variable to JSON object and print it like JSON object?
I simply want to pass variable value in JSON and print it like JSON which can also be used in console.table(obj)
With Stringify:
var name = "someName";
const json = JSON.stringify('{"result":'+name+', "count":42}');
const obj = JSON.parse(json);
console.log(obj);
Without stringify
var name = "someName";
const json = '{"result":'+name+', "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Using \"variableName\" it gets value in \"...\" and not the variable value
var name = "someName";
const json = '{"result":\"name\", "count":42}';
const obj = JSON.parse(json);
console.log(obj);
Solution:
var debugJSON = [];
var section_number = 1;
var i = 25;
var x = section_number-i;
tempJSON = {
"section" : section_number,
"index" : i,
"fieldname" : x,
"isValid" : "not required"
};
debugJSON.push(tempJSON);
console.log(debugJSON);
//console.table(debugJSON); //Problematic on Chrome Browser and Stack Overflow
JSON is a text representation of some data structure.
Unless you write a JSON encoder (and you don't), you don't have any reason to produce JSON manually. Attempting to generate JSON using string concatenation fails if the variable strings (name in this case) contain quotes or backslash. Escaping them could produce valid results but the code becomes bloated and difficult to read without any gain.
JavaScript provides the method JSON.stringify() to produce a JSON from any data and this is the best way to generate JSONs.
All you have to do is to build the data structure that you need to encode. In your example, the data structure is an object:
let name = "someName";
const original = {
result: name,
count: 42,
}
// encode
const json = JSON.stringify(original);
console.log(json);
// decode
data = JSON.parse(json);
console.log(data);
Running the code snippet here in page is not relevant because the output that it produces looks similar for both calls of console.log().
Run the code using Node.js or run it in the browser's console to see the values of json (it is a string) and data (it is an object).
A JSON is quite literally a JavaScript object, so you don't treat it as a string, you work with objects, which you can later stringify if need be.
In your case, you don't want to pass a variable in a string, you should pass it in an object like so:
// Declaration of name
let name = 'someName';
// Create object and store name
const json = {
result: name,
count: 42
};
// Log object as JSON and as string
console.log(json);
console.log(JSON.stringify(json));
The first log returns your object as exactly that, an object, the second log, converts it into a string to do so as you please with it!

Parse json string array returned from c#

I am returning a JSON array string from c#, which is a list of classes I want to read county element in a class and add it to a js array. How can I parse this string?
{"d":"[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"}
The d property is itself JSON, so you need to parse that separately from the response to give you an array of objects which you can work with, something like this:
var response = {
"d": "[{\"county\":\"PA\",\"state\":\"Mountur\"},{\"county\":\"PA\",\"state\":\" Beaver\"}]"
}
var arr = JSON.parse(response.d);
arr.forEach(function(obj) {
console.log(obj.county + ' ' + obj.state);
});
console.log(arr);

How to extract value from an Array in Javascript

I am querying my db in node and have got the result in the form of an object like this - [ [1234] ].
I want to extract this value and convert it into a string and then pass it onto the client side. I have written the other required code but I am not able to get value from this object. Can anyone help me in getting the value and converting it to string?
Since, the result you've got is a two-dimensional array, you can get the value and convert it into a string (using toString() method) in the following way ...
var result = [ [1234] ];
var string;
result.forEach(function(e) {
string = e.toString();
});
console.log(string);
** this solution will also work if you have multiple results, ie. [ [1234], [5678] ]
You have a nested array, meaning that you have an array inside another array:
[ [1234] ]
// ^-^====^-^
To get the first value of the parent array, use the square brackets: [0]. Remember that indexes start at 0!
If you have val = [[1234]], val[0] gets the enclosed array: [1234]. Then, 1234 is a value in that array (the first value), so you use the square brackets again to get it: val[0][0].
To convert to string, you can use + "" which forces the number to become a string, or the toString() method.
var val = [[1234]];
var str = val[0][0] + "";
// or val[0][0].toString();
console.log(str, typeof str);
You can read more about arrays here.
var response = [ [1234] ];
console.log(response[0][0]);
to extract values from a string array or an array we can use .toString()
Ex:
let names = ["peter","joe","harry"];
let fname = names.toString();
output = peter ,joe,harry
or
let name:string[] = this.customerContacts.map(
res => res.firstname
let fname =name.toString();
Using De-structuring Array concept:
const arr = [[1, 2, 3, 4, 5]];
const [[p, q, r, s, t]] = arr;
console.log(p, q, r, s, t);
Output: 1 2 3 4 5

Get data from this json string

I have a json string
["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]
I need to get at the data only and I want to extract the string to get the following :
https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
I have tried to use JSON.parse but this does not seem to work
Any help woul dbe appreciated
[] represents an array on JSON. {} represents an Object.
So in order to fetch the first element from you json string, you have to parse the string as a JSON element ;
var arr = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]');
OR when you HAVE a json array already;
var arr = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
Then, go on and fetch the first value from your array which has index 0 as in all programming languages.
var url = arr[0];
It's seems to be a normal array not a JSON, but if you want you can treat it as JSON:
var image = JSON.parse('["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]')[0];
console.log(image); //https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg
Be aware of the difference between an array, and a JSON object.
I have given some examples of the differences and how to access them.
// This is an array containing 1 value.
myobj = ["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"];
// it can be accessed by either the array name (since it only hase one value) or the array name and index of the value in cases where the array actually has more than one value.
var example1 = [myobj];
document.write("This is my single value array:<br>" + example1 + "<br><br>");
// This is probably best practice regardless of the number of items in the array.
var example2 = myobj[0];
document.write("Now im specificing the index, incase there are more that one urls in the array:<br>" + example1 + "<br><br>");
// This is a JSON object
myJsonObj = {"url":"https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"}
// You access the value of the URL like this:
var example3 = myJsonObj.url;
document.write("Here is the value from a JSON object:<br>" + example3 );
Hope this helps
Just use parse function:
var text = '["https://upload.wikimedia.org/wikipedia/commons/5/57/Cassini_Helene_N00086698_CL.jpg"]';
var obj = JSON.parse(text);
https://jsfiddle.net/esouc488/1/

Stringify an JS Object in Asc order

I have an js object like
{
a: 1,
b: 2,
c: 3
}
I wanted to stringify the above object using JSON.stringify with the same order. That means, the stringify should return me the strings as below,
"{"a":"1", "b":"2", "c":"3"}"
But it is returning me like the below one if my js object has too many properties say more than 500,
"{"b":"2", "a":"1", "c":"3"}"
Is there any option to get my js object's json string as in sorted in asc.
If the order is important for you, don't use JSON.stringify because the order is not safe using it, you can create your JSON stringify using javascript, to deal with string values we have 2 different ways, first to do it using regexp an replace invalid characters or using JSON.stringify for our values, for instance if we have a string like 'abc\d"efg', we can simply get the proper result JSON.stringify('abc\d"efg'), because the whole idea of this function is to stringify in a right order:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = JSON.stringify(key);
value = JSON.stringify(value);
arr.push(key + ':' + value);
}
return "{" + arr.join(",\n\r") + "}";
}
var jsonString = sort_stringify(yourObj);
If we wanted to do this not using JSON.stringify to parse the keys and values, the solution would be like:
function sort_stringify(obj){
var sortedKeys = Object.keys(obj).sort();
var arr = [];
for(var i=0;i<sortedKeys.length;i++){
var key = sortedKeys[i];
var value = obj[key];
key = key.replace(/"/g, '\\"');
if(typeof value != "object")
value = value.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
arr.push('"' + key + '":"' + value + '"');
}
return "{" + arr.join(",\n\r") + "}";
}
The JavaScript objects are unordered by definition (you may refer to ECMAScript Language Specification under section 8.6, click here for details ).
The language specification doesn't even guarantee that, if you iterate over the properties of an object twice in succession, they'll come out in the same order the second time.
If you still required sorting, convert the object into Array apply any sorting algorithm on it and then do JSON.stringify() on sorted array.
Lets have an example below as:
var data = {
one: {
rank: 5
},
two: {
rank: 2
},
three: {
rank: 8
}
};
var arr = [];
Push into array and apply sort on it as :
var mappedHash = Object.keys( data ).sort(function( a, b ) {
return data[ a ].rank - data[ b ].rank;
}).map(function( sortedKey ) {
return data[ sortedKey ];
});
And then apply JSON.stringy :
var expectedJSON = JSON.stringify(mappedHash);
The output will be:
"[{"rank":2},{"rank":5},{"rank":8}]"

Categories