Is JSON in JavaScript stored in HashMap? - javascript

I searched JSON and HashMap, there are many questions about "how to convert json to hashmap". So, they are different, and how can i use hashmap in js?

Short answer would be “no”, because JSON is simply a interchange format written and parsable as a JavaScript object. If you want something like a hash map, you probably would just use an Object not-so-primitive, defining and deleting keys or values respectively:
var mapObj = {};
mapObj[key] = 'value';
delete mapObj[key];
There is also the Map object that might fit such an use, new in ES6:
var mapObj = new Map();
mapObj.set('key','value');
mapObj.get('key');
mapObj.delete('key');
You can serialize JavaScript objects by calling stringify on them and then parse them again:
var stringJSON = JSON.stringify(mapObj); // check your object structure for serializability!
var objsJSON = JSON.parse(stringJSON);
Serializing a Map is a bit different. If serialisable, you can do it anyway by using Array.from() and entries():
var strMap = JSON.stringify(Array.from(mapObj.entries()));
var mapObj = new Map(JSON.parse(strMap));

Wikipedia article states clearly that JSON is just text:
[JSON] uses human-readable text to transmit data objects
JSON is stored inside strings in Javascript. Javascript objects are essentially hashmaps. You can use JSON.parse() to convert a JSON string to an object.

Related

Parse result of API response that looks like JSON array (of type string) back into array?

How can we convert an array of type string back into array.
var arr = '[ "abc", "def"]';
console.log(typeof arr) ==> String
How can i convert it back into an array?
I am getting this array in form of string from an API response. and these are errors which can be multiple. I want to convert them into an array such that i can display them on their correct positions.
If your string is really as shown in your edit (not your original question), it's valid JSON, so you could use JSON.parse:
var str = '["abc", "def"]';
var arr = JSON.parse(str);
Since your array syntax conforms to that of a JSON array: Use a JSON parser.
Browsers have one built-in these days.
arr = JSON.parse(arr);
For a more general approach, you would need to look at eval, but that has numerous drawbacks (including issues of scope, speed, and security).
You can't convert it back, since you don't actually have an array.
an array should be created without the single quotes ... you are creating a string, you want to do something like the following if you want to create an array.
var arr = ["string 1","string 2"];
UPDATE
Since you updated your question, with information regarding why you had a string, you can follow the suggested solution:
JSON.parse(arr);
Use JSON.parse() to convert the JSON string into JSON object.
DEMO
var arr = '[ "abc", "def"]';
console.log(typeof arr); // string
var arr = JSON.parse('[ "abc", "def"]');
console.log(typeof arr); // object

Converting GeoJSON object to Javascript Array

I need to convert a GeoJSON output from a server to a Javascript array; I have done some searches and they were for the 'regular' JSON outputs and not the GeoJSON. Here is the output from the Server:
{"type":"FeatureCollection","features":[{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}
And here is what I need (note, no quotation on the 'features' variable needed):
features = [{"type":"Feature","property":"blah"}, {"type":"Feature","property":"blah2"}]}
I think I need to find the 'features' property and then loop through its objects? Thanks!
A GeoJSON object is still a JSON object (it's the first thing their documentation says).
http://geojson.org/geojson-spec.html
If you want to store the features PROPERTY of a GeoJSON object, access the property value as you would normally after conversion to a javascript object and push that property into a new variable, or use as is.
var geoObject = JSON.parse(geoJSONObject);
var features = [];
features = geoObject.features;

Access JSON object to get Resource Bundle key/value pair

I know how to access key value pair from JSON object but in my case, the resource bundle keys are mapped to values.
e.g.
var json = {"label.name.first":"foo","label.name.second":"bar"};
Here json.label.name.first doesn't give me "foo".
Can someone help me with this?
Due to using the period character (.) in the key name, you need to use the [] notation to access its value.
console.log( json['label.name.first'] );
Additionally, you have a JavaScript object, not JSON.
The difference between a JavaScript object or JSON is that JSON is always a string. Secondly, JavaScript objects don't require the same quote standards on the key names.
If you just consider the string below, then yes it can be considred JSON (this is why if you paste it into a JSON parser, it tells you it's valid JSON):
{"label.name.first":"foo","label.name.second":"bar"}
However, if you assign that directly to a JavaScript variable then you have a JavaScript object literal, not JSON. This is because JSON is also a valid JavaScript object/array literal when it is not contained in a string:
var obj = {"label.name.first":"foo","label.name.second":"bar"};
If you were to use it as a string, then it is JSON:
var json = '{"label.name.first":"foo","label.name.second":"bar"}';
// json is a string, so it's JSON
var obj = JSON.parse(json); // parse the JSON into an object
The confusion is quote common because the JSON format is very similar to the format of JavaScript object and array literals.
Do this:
json["label.name.first"]
However, I think you are misunderstanding the . notation.
And BTW your json isn't a JSON, it is a javascript object and not its notation.
It's json["label.name.first"] that would get you "foo". Since your property's name contains characters that cannot be used in variable names.
If you're expecting to access these properties using the syntax json.label.name.first then your JSON needs to be:
var json = {
"label":{
"name":{
"first":"foo",
"second":"bar"
}
}
}
This is not right way to create object, you should create one like this.
var json={"label":{"name":{"first":"foo","second":"bar"}}};
it will also work as json string

Serializing and unserializing an array in javascript

I'm using the tag-it library for jquery to make a tagging system (a bit like the stackoverflow one).
After the user types his tags the library returns a javascript array that I want to save in a MySQL database. I didn't find a serialize and unserialize function in javascript.
Before coding my own function I'd like to make sure I'm not reinventing the wheel here. It seems crazy that there is no native way to save an array to a database and then use it again.
tl;dr => how can I save a javascript array in a MySQL database to reuse it later ?
You can use JSON.stringify() (MDN docu) and JSON.parse() (MDN docu) for converting a JavaScript object into a string representation to store it inside a database.
var arr = [ 1, 2, 3 ];
var serializedArr = JSON.stringify( arr );
// "[1, 2, 3]"
var unpackArr = JSON.parse( serializedArr );
// identical array to arr
If your backend is written in PHP, there are similar methods to work with JSON strings there: json_encode() (PHP docu) and json_decode() (PHP docu).
Most other languages offer similar functionalities for JSON strings.
You can use JavaScript Object Notation(JSON) format.
Javascript supports these methods:
JSON.stringify -> serializes object to string
JSON.parse -> deserializes object from string
How about just JSONing it?
var arr = [1,2,3];
var arrSerialized = JSON.stringify(arr);
...
var arrExtracted = JSON.parse(arrSerialized);
By the way, JSON is often used for serializing in some other languages, even though they have their own serializing functions. )

How to use JSON to re-build the Javascript Object?

I have an object like this:
var someObj = Class.create ({
initialize: function(objName){
this.objName = objName;
}
});
I can use
o = new someObj("objName");
to make an obj. I can use Object.toJSON(o) to change the o to become a JSON String,
but I want the JSON String convert back to someObj, so, I use eval() to pass the
JSON String to become an object, but the question is, it can become a JS Obj,
but the constructor of "o" is not someObj. How can I eval the JSON String by using
"someObj" as the constructor?
JSON strings cannot represent objects with member functions, so the only thing you will get out of a JSON string is raw data. Assuming the toJSON method results in a JSON string representing an object with all the non-function members of your class instance, you should be able to take the resulting object and attach the prototype to get all the functions back. For example, using jQuery's handy extend function:
var o = new someObj("objName");
var json = Object.toJSON(o);
var json_obj = eval(json);
$.extend(json_obj, someObj.prototype);
json_obj.someMethodDefinedOnsomeObj()
Depending on how the framework you are using to represent classes in JavaScript makes use of the prototypal object model, your milage may very with the above example. Also, using eval() creates a security hole, so if you do not trust where the JSON string is coming from, you should use a different de-serialization method. Just for full coverage, here is how I did it with raw prototypes:
function Animal(name){
this.name = name;
}
Animal.prototype.talk = function(){
console.log("My name is "+this.name);
}
var a = new Animal("Brendan Eich");
a.talk();
var json = '{name: "Tim Berners-Lee"}'
var b = eval(b);
$.extend(b, Animal.prototype);
b.talk();
In a firebug console this produces the output:
My name is Brendan Eich
My name is Tim Berners-Lee
See JSON revivers at http://json.org/js.html
var myObject = JSON.parse(myJSONtext, reviver);
The optional reviver parameter is a
function that will be called for every
key and value at every level of the
final result. Each value will be
replaced by the result of the reviver
function. This can be used to reform
generic objects into instances of
pseudoclasses, or to transform date
strings into Date objects.
you're using prototypejs right? i've always found that tricky and ended up just making my own initializer that read in an object that had been evaled or the json string itself.

Categories