I have a Javascript problem where I need to be able to store data like follows:
MainArray(Array(JavaScript Object, JavaScript Object, etc etc..), Array(JavaScript Object, JavaScript Object, etc etc..), etc etc..)
The main array has 10 sub arrays, these sub arrays then contain any number of JavaScript Objects.
I need an efficient way of storing the data this way and need to know how to parse to JSON/decode back to a manageable structure in Javascript.
The reason for this structure is because the Java program I'm communicating with uses this structure.
I'm able to use jQuery if that makes any difference.
Your structure appears to look like this
var myVariable = [
[
{ }, { }, { }
],
[
{ }, { }, { }
]
]
This can be JSON stringified. It yields "[[{},{},{}],[{},{},{}]]"
Use JSON.stringify and JSON.parse, respectively.
Related
First: I'm aware of other solutions like Removing unused information from JSON but I'm looking for a more dynamic approach.
I have two json objects. The first one looks like this:
{
"key2":"value2",
"key3":{
"key4":"value4",
},
"key6":"value6",
}
And the second json objects looks like this:
{
"key1":"value1",
"key2":"value2",
"key3":{
"key4":"value4",
"key5":"value5"
},
"key6":"value6"
}
Is there a dynamic approach (java or javascript) to ensure that only the matching keys between both json objects are returned? In this case, key1 and key5 should be deleted from the second json because this keys are not present in the first one, but the first array does not always look the same.
I am using JSON to carry information from NodeJS (server side) to my client side. When I try to parse the JSON in the client side, it outputs only the last element, in this case, 'name: "Sam"'. I want all the elements to be outputted.
I have tried using an array and a variable to be assigned the parsed data. I have also directly tried logging it to the console with: [console.log(JSON.parse(this.response));]. All three gave the same result.
The first console.log returns all the elements in JSON form. The second one returns only the last one. There are 3 elements in total.
I expect all the elements to be assigned to the variable.
request.open('GET', 'http://localhost:3000/listofvoted', true);
request.onload = function () {
console.log(this.response)
console.log(JSON.parse(this.response));
}
request.send();
The JSON I receive:
{
"name": "Bran",
"name": "Ram",
"name": "Sam"
}
Although JSON (which is just a notation) allows for duplicate key names, the guidance is that that they SHOULD be unique. If you want to use JSON to create a JavaScript Object, then you are constrained by the fact that a JavaScript Object cannot have duplicate keys. So although you have valid JSON, it cannot be represented by a JavaScript Object and therefore it will not survive a round trip of being parsed (JSON converted to a JavaScript Object) by JSON.parse and then converted back to JSON.
For your own convenience of working in JavaScript, you could consider changing the JSON representation of your information so that it can be represented as a JavaScript Object.
Here are some alternative ways of representing what you have that may work:
Use an array of discrete objects:
[
{ "name": "Bran" },
{ "name": "Ram" },
{ "name": "Sam }"
]
Use an array of names:
{
"names": [ "Bran", "Ram", "Sam" ]
}
As a final, heavy-handed approach, you don't have to convert your JSON to a JavaScript object. You can parse it using a parser that allows you to provide your own handlers for the syntactic elements that occur in the JSON string and you can handle the duplicate keys in whatever way you wish. May I suggest the clarinet library for doing so.
See also, How to get the JSON with duplicate keys completely in javascript
I am working on a project that has JSON format output. I need a clarity on the JSON array structure. So There are fields that are multiple entry like an array. If an element is an array but has only one value, does it still include an array node '[' in the structure?
Example:
This is a sample JSON element which is an array and has multiple values.
"Talents": [
{
"Items": "test"
},
{
"Items": "test"
}
]
If this element does not have multiple values, will it appear as below?
"Talents":
{
"Items": "test"
}
The '[' does not appear for an array type element with single value. Can someone Pls clarify this?
Single-item arrays will still include the array brackets in JSON format, as they are still arrays. In other words, there is no such native mechanism which converts single-item arrays to a non-array representation. So with your single-item example, it would be represented like this:
"Talents": [
{
"Items": "test"
}
]
You can easily test this out with some simple code:
let jsonSingleItem = { "Talents": [ {"Items": "item1"} ] };
let arraySingleItem = [ {"Items": "item1"} ];
console.log(JSON.stringify(jsonSingleItem));
console.log(jsonSingleItem);
console.log(arraySingleItem);
Which yields the following output:
{"Talents":[{"Items":"item1"}]}
{ Talents: [ { Items: 'item1' } ] }
[ { Items: 'item1' } ]
So in all cases (a stringified JSON object, native JSON, and a javascript array) the single item is still in an array.
Note: It is not uncommon that a consumer of an API will send data (i.e. JSON) in ways which are outside the agreed-upon contract/schema that API defines, and this (sending an object instead of a single-object array when there is just one item) is one example I have seen before. It would be up to the owner/developer of the API as to whether they build in flexibility to handle input which deviates from the API schema.
Square brackets ("[]") denotes JSONArray which in your case can access like
Talents[0]
will return
{
"Items": "test"
}
In second case, curve brackets denotes an JSON object. If you want to access value of items. Than you can by
Talents.Items
OR
Talents["Items"]
will return
"Test"
for complete reference,
JSON Syntax
I'm very new to mongoDB and am trying to insert an object to the database. (Wow, much more fun than mySQL...). I'm using strongloop's loopback framework and its mongoDB connector.
The object is a xml2js parsed xml message I receive, after parsing and inserting to mongo it looks like this:
{
"_id": ObjectID("55c61ee9391da88435c5753f"),
"offerChange": [
{
"foo": [
"bar"
],
"baz": [
"foo"
]
}
]
}
as you can see, all the key's values are arrays, though all of them contain only one value. Obviously I can convert them to strings before the insert or during xml parsing, but that would require looping over all the object's keys or more work for the worker in the first place, which I'd like to avoid. The real object is much bigger than above shown.
Is there a way to tell mongoDB to automatically convert arrays that have only one value to a string before or after the document gets created?
You need not loop through and convert from array to string in application/database. xml2js provide a neat way to return string if there is only one item and array if there are more items.
explicitArray (default: true): Always put child nodes in an array if
true; otherwise an array is created only if there is more than one.
Initiate your parser as follows
parseString(xml, {explicitArray: false}, function (err, result) {
});
I'm a perl programmer learning javascript. In perl, I would frequently use hashes to create 'data structures' from data returned from a database query. For example, I would build hashes like this:
*loop through list of data*
push(#{$hash{$key1}{$key2}}, [$value1, $value2, $value3, $value4]);
*endloop*
this would add a reference to the list of four values to a list in the hash (with multiple keys).
I'm having a hard time finding information on how I would implement a similar structure in javascript. My goal is to read in a JSON file that has a list of objects (which has no particular order) and turn it into a hash so it can be sorted by the keys and then display it in an HTML table.
Perhaps this is the wrong way to think about this problem and javascript will have a different approach. I'd like to know if what I'm trying to do is possible, the code to create the hash, and the code to access the hash.
Thanks,
Rob
This is my straight translation, tested at the Google Chrome console prompt >
> hash = {}
Object {}
> hash["key1"] = {}
Object {}
> hash["key1"]["key2"] = []
[]
> hash["key1"]["key2"].push([ 'value1', 'value2', 'value3', 'value4'])
1
> hash
Object {key1: Object}
> JSON.stringify(hash, null, 2)
"{
"key1": {
"key2": [
[
"value1",
"value2",
"value3",
"value4"
]
]
}
}"
Hash in Perl is just set of key/value pairs. Javascript has similar data structure - Objects. You could do what you want
> a = {}
{}
> a.res = []
[]
> a.res.push([1,2,3])
1
> a.res.push([3,"sd",1])
2
> a
{ res:
[ [ 1, 2, 3 ],
[ 3, 'sd', 1 ] ] }
Javascript does not have an ordered hash and a lookup with multiple keys. You can use the properties of an object to create a lookup by a single unique key and you can then build on that notion as needed. See this answer for an idea how to implement a simple form of hash or set in javascript.
The basic idea is that you create an object and then add key/value pairs to it:
var myLookup = {};
myLookup[key1] = value1;
myLookup[key2] = value2;
Then, you can look up a value by the key:
console.log(myLookup[key1]); // shows value1
If you want more specific help, you will have to be more specific in your question. Show us what the JSON you start with and describe exactly how you want to be able to access it so we can figure out what type of JS data structure makes the most sense to put it in. Remember, once the JSON is parsed, it is already in a javascript data structure at that point so the it becomes a question of what kind of access you need to make to the data to understand whether the data should be restructured with certain key lookups?
It is generally best to concentrate on problem/solution and NOT on trying to do something the same way another language does it.