How to create a JSON object with duplicate keys [duplicate] - javascript

This question already has answers here:
Sailsjs Mysql ORM multiple query on the same table field
(2 answers)
Closed 7 years ago.
I'm working on a SailsJS project and I need to create a json object for my ORM search to work, This is how the search should be performed
Venue.find({
is_published: true,
restaurant_services: {
contains: '"delivery":"1"',
contains: '"takeout":"1"'
},
restaurant_specialties: {
contains: '"breakfast":"1"',
}
}).exec
So as you may see the JSON object inside the Find() is the one O need to create and the values inside has duplicate keys.

You can't. Your should try using something like this instead:
Venue.find({
is_published: true,
restaurant_services: {
contains: ['"delivery":"1"','"takeout":"1"']
},
restaurant_specialties: {
contains: [ '"breakfast":"1"' ]
}
}).exec
Or this:
Venue.find({
is_published: true,
restaurant_services: {
contains: {"delivery":"1","takeout":"1"}
},
restaurant_specialties: {
contains: { "breakfast":"1" }
}
}).exec

The problem is that the {... } Jason represents a map and therefore can't have duplicate keys. Although duplicate keys are strictly not Syntax errors but they are going to able also not going to work as expected with browsers or json libraries. If you can't change the syntax for your json object then you will have to produce that json by string concatenation instead of the normal Javascript type approach.

Related

Can I set Javascript object keys based on a variable, e.g index of a loop? [duplicate]

This question already has answers here:
Accessing an object property with a dynamically-computed name
(19 answers)
Closed 12 months ago.
I'm looping over an array, getting data from an API on each iteration.
I want to pass data from all iterations of the loop from my express server to the browser using res.json(), so I want to create an object that contains an object of data for each API call, as well as some other key-value pairs that will be created depending on what is returned.
e.g.
on loop index 0:
artist0:
{
data: 'data',
moreData: 'more-data'
}
on loop index 1:
artist1:
{
data: 'data',
moreData: 'more-data'
}
etc
I would use an array, but one of the calls (at random) will result in another key value pair,
e.g.:
correctAnswer: 'a_url.com'
this will be generated by one of the earlier API calls at random, so I cant get it at the other end using its array index.
I need the key 'correctAnswer', so I also need each object of API data to be identified by which API call it came from.
Short question: Can I name keys based on variables?
As always, your kind help is greatly appreciated :-)
You could solve this by not putting artists directly in the object, like this, using a array inside a single attribute of the object:
{
"artists": [
{
"data": "data",
"moreData": "more-data"
},
{
"data": "data",
"moreData": "more-data"
}
],
"correctAnswer": 3
}
Or alternatively, if you really want a dynamic key you can use
{
[`artist${artistIndex}`]: {'data': 'data'}
}

Can I Rely on the Order of a JSON Array? [duplicate]

This question already has answers here:
Is the order of elements in a JSON list preserved?
(5 answers)
Closed 6 years ago.
It's obvious that I can't rely on the ordering of key-value pairs in JSON. For example, a JSON parser could interpret
{
"someKey" : "someValue",
"anotherKey" : "anotherValue",
"evenAnotherKey" : "evenAnotherValue"
}
as
{
"anotherKey" : "anotherValue",
"someKey" : "someValue",
"evenAnotherKey" : "evenAnotherValue"
}
legally, but could I rely on the ordering of a JSON array? For example, could a JSON parser interpret
{
"arrayKey" : ["firstElement", "secondElement", "thirdElement"]
}
as
{
"arrayKey" : ["secondElement", "firstElement1", "thirdElement"]
}
legally? I'd assume not, but my friend told me that I was incorrect.
Yes, you can! Arrays are made, so that order matters! That is what divides Objects from Arrays. Especially in JS and JSON.
Arrays and lists are always ordered. That's the point of having arrays and lists - their position is their index.
Incidentally, since ES5 the order of objects (what you call key-value pairs) are guaranteed as well. But not in a straightforward way.
For objects, any key that is a number will be ordered before non-numeric keys and will be ordered numerically. But all other keys are guaranteed to be in insertion order. So the following object:
{
hello : "world",
foo : "bar",
"22" : "first"
}
must be returned as:
{
"22" : "first",
hello : "world",
foo : "bar"
}
Currently all browsers support this and node.js support this but not all javascript cross-complier (like Babel) support it.
Personally I don't like to treat unordered data structures like objects as ordered. But it looks like the js community disagrees. Go for example deliberately randomises the ordering of maps to prevent people from relying on any accidental stable ordering from an implementation of the language.

Converting JSON string with multiple arrays to Javascript object [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 6 years ago.
I have a json file in a structure like this one:
{
"items":[
{
"username":"abc",
"orderID":"1234",
"commentHistory":[
{
"comment":"Comment Date: 2016/12/09 13:44:23"
},
{
"comment":"Failed: 2016/12/08 11:42:12"
}
],
.........
}
]}
Where an array "items" is storing the data and there is another array inside to store the comment history.
I know I can get the data using JSON.parse, like the example from W3School (http://www.w3schools.com/js/tryit.asp?filename=tryjs_json_parse).
However, the example only including one array in it. So if I want to get the data inside the second array, ie: comment inside comment history... how the syntax would look like if I want to access the data of an array inside another array? Thank you so much.
Not much syntax at all. This code should work for any number of comments within a given history.
JSON.parse(jsonString).items[0].commentHistory.map(function (e) {
return e.comment
})
Here's a snippet so you can see for yourself:
var data = {
"items":[
{
"username":"abc",
"orderID":"1234",
"commentHistory":[
{
"comment":"Comment Date: 2016/12/09 13:44:23"
},
{
"comment":"Failed: 2016/12/08 11:42:12"
}
],
}
]}
console.log(data.items[0].commentHistory.map(function (e) {
return e.comment
}))

Javascript multi-dimensional array to and from JSON (jQuery?)

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.

Why can't I access JSON objects by key in JavaScript?

This is my JSON object:
{ text: 'stuff',
user: 'user1
}
when I run a typeof jsonObj, I get object. When I run an jsonOb.length, I get undefined. When I tried to access the text property via console.log(jsonObj.text), I get undefined.
So how can I properly access everything in JavaScript?
I don't want to use jQuery as this is all node.js programming so it's serverside.
UPDATED - full JSON
{ text: '#junk_666 おかえりか',
user:
{ display_name: 'mono',
screen_name: 'monochrm',
klout_score: null,
location_str: '画面の前',
utc_offset: '32400' },
venue_id: 1304409836517,
match_type: 'twitter',
tweet_id: '116494264137023489',
created_at_unix: 1316609371,
meta:
{ matchedPhrase: 'junk',
venueName: 'deletemepls really long name' },
tags: [ '' ],
indexed_at_unix: 1316609416 }
The json seems to be invalid
{
"text": "stuff",
"user": "user1"
}
I copied and pasted your object into a FireBug console and it recognized it.
If you need to count the number of key/value pairs, you can use a function such as this one to do it:
function numMembers(o) {
var i=0;
for (a in o) {
i++;
}
return i;
}
You should be able to access the value of the text property via jsonObj.text. Are you sure that your object is being referenced by jsonObj? Also, can you access the values for simpler objects such as the ones mentioned in other posts if you create them? Furthermore, does anything work if you use only ASCII characters? For some reason, it might not be handling some of the non-Latin characters properly.
First, what you have is not JSON because JSON requires property name to be in double quotes. It is a valid JavaScript object literal though, so I'll assume that's how you're using it.
Secondly, JavaScript objects in general do not have a length property. Arrays do.
There's no problem with your object literal so there must be some other problem elsewhere in your code.
Try this:
{ text: 'stuff',
user: 'user1'
}
You left off an apostrophe.
Now that you've posted your full JS code (that's not JSON, as #josnidhin points out)... works fine in jsFiddle. http://jsfiddle.net/Rs9R4/ I don't believe a JS Object has .length, just Arrays.

Categories

Resources