I have a string of the form:
"{ "name" : "XYZ", "email" : "XYZ#ABC.com" } { "name" : "PQR", "email" : "PQR#ABC.com" } "
How do I split this string/parse it and ID it in a proper way to display just the names and the emails on the client side?
Expect something like this ---
XYZ
XYZ#ABC.com
PQR
PQR#ABC.com
Where is this string coming from? It looks like a set of JSON objects concatenated together? To munge it into a JSON string you can do the below. But this is ugly, better to fix the source of the string so its proper JSON.
let string = '{ "name" : "XYZ", "email" : "XYZ#ABC.com" } { "name" : "PQR", "email" : "PQR#ABC.com" } ';
string = string.replace(/}\s*{/,"},{");
console.log(JSON.parse(`[${string}]`));
I want to get the value of the field 30 in the object (in the array test) with the id ePce6fBAHx9KeKjuM.
{
"_id" : "nAwt3b76c24mZfqxz",
"title" : "test",
"test" : [
{
"4" : false,
"15" : false,
"30" : false,
"75" : true,
"id" : "ePce6fBAHx9KeKjuM"
}
]
}
So this result would be false
I tried something like
var result = Collection.findOne({_id: 'nAwt3b76c24mZfqxz'}).test;
But this would give me the complete array. But I need the selected object and only a selected field of this object (ie. 30).
test is just a JS array. Use normal array syntax to access its elements:
var result = Collection.findOne({_id: 'nAwt3b76c24mZfqxz'}).test["30"];
EDIT:
To retrieve the whole object with only 1 element of the array use projection, as of zangw's answer. Following your comment to test element itself:
db.getCollection('a').find(
// put your nested document's condition instead of `$exists`
{_id: 'nAwt3b76c24mZfqxz', test:{ $elemMatch: { "30": {$exists: true}}}},
// add other fields you like to retrieve, e.g. "title":1
{"test.30":1}
)
Try this one
Collection.find({{_id: 'nAwt3b76c24mZfqxz'}}, {'test.30': 1, 'test.id': 1});
To select the whole test array as following without _id
Collection.find({{_id: 'nAwt3b76c24mZfqxz'}}, {'test': 1, '_id': 0});
I receive the following JSON string from an API function.
"Inbound": {
"callRelatedFields": ["ANI",
"DNIS"],
"objects": {
"Contact": [{
"displayName": "Name",
"apiName": "Name"
},
{
"displayName": "Email",
"apiName": "Email"
}],
"Account": [{
"displayName": "Account Name",
"apiName": "Name"
},
{
"displayName": "Phone",
"apiName": "Phone"
},
{
"displayName": "Fax",
"apiName": "Fax"
}],
"cnx__Phone__c": [{
"displayName": "Phone Name",
"apiName": "Name"
},
{
"displayName": "Phone Number Line 1",
"apiName": "cnx__Phone_Number_Line_1__c"
},
{
"displayName": "Phone Number Line 2",
"apiName": "cnx__Phone_Number_Line_2__c"
},
{
"displayName": "Type",
"apiName": "cnx__Type__c"
},
{
"displayName": "Location",
"apiName": "cnx__Location__c"
},
{
"displayName": "Call Manager",
"apiName": "cnx__Call_Manager__c"
},
{
"displayName": "Mac Address",
"apiName": "cnx__Mac_Address__c"
}]
},
"screenPopSettings": {
"screenPopsOpenWithin": "ExistingWindow",
"SingleMatch": {
"screenPopType": "PopToEntity"
},
"NoMatch": {
"screenPopType": "DoNotPop"
},
"MultipleMatches": {
"screenPopType": "DoNotPop"
}
}
}
The order of the objects inside "objects" is important!
But when i parse this JSON string with JSON.parse, the order of those objects is lost.
Is there any good way to keep the order of those objects after they are parsed.
I tried to manipulate the string and convert the whole "objects" into an array, but this turned out to become way too complicated and hacky.
I have a suspicion that the thing that makes you think the keys have changed order is that Chrome devtools show objects with their keys sorted in alphabetical order. Whereas if you use Object.keys() or the equivalent JS to manually iterate through the keys, you will find they come out in the order they were defined in the JSON string.
Here is the equivalent JS for Object.keys():
function objectKeys(obj) {
var keys = [];
if (!obj) return keys;
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
}
When I call this with the objects part of the parsed object I get the following array:
["Contact", "Account", "cnx__Phone__c"]
Unfortunately object properties are unordered in JavaScript so you shouldn't rely on being able to iterate over them in a particular sequence.
I would suggest accessing the properties by name in the order you need them, rather than just iterating over the list.
As per the JSON standard, an object is unordered. So if you care about the order "Contact", "Account", "cnx__Phone__c", put them in an array ([]).
Maybe it's enough to put the property names themselves in an array next to the .objects themselves, so that you still can access them by their names. Many structures are valid solutions.
This solution works only if the properties and the data does not contain one of these characters: {, } and :.
Maybe you replace the curly brackets to square brackets and ": to #",. After that, you can the JSON string parse and get all objects replaced by arrays. The reading is: first value is the property (marked with # at the end) and the second value is the value.
The replacement machanism shuld be improved, in particular the replacement of ":, which can sometimes be wrong, and the search of the curly brackets.
var json = '{"Inbound":{"callRelatedFields":["ANI","DNIS"],"objects":{"Contact":[{"displayName":"Name","apiName":"Name"},{"displayName":"Email","apiName":"Email"}],"Account":[{"displayName":"Account Name","apiName":"Name"},{"displayName":"Phone","apiName":"Phone"},{"displayName":"Fax","apiName":"Fax"}],"cnx__Phone__c":[{"displayName":"Phone Name","apiName":"Name"},{"displayName":"Phone Number Line 1","apiName":"cnx__Phone_Number_Line_1__c"},{"displayName":"Phone Number Line 2","apiName":"cnx__Phone_Number_Line_2__c"},{"displayName":"Type","apiName":"cnx__Type__c"},{"displayName":"Location","apiName":"cnx__Location__c"},{"displayName":"Call Manager","apiName":"cnx__Call_Manager__c"},{"displayName":"Mac Address","apiName":"cnx__Mac_Address__c"}]},"screenPopSettings":{"screenPopsOpenWithin":"ExistingWindow","SingleMatch":{"screenPopType":"PopToEntity"},"NoMatch":{"screenPopType":"DoNotPop"},"MultipleMatches":{"screenPopType":"DoNotPop"}}}}';
json = json.replace(/{/g, '[').replace(/}/g, ']').replace(/"\:/g, '#",');
json = JSON.parse(json);
document.write('<pre>' + JSON.stringify(json, 0, 4) + '</pre>');
#GregL is right the JSON parsed came in alphabetic or in case of a number in ascending order and to keep the order you'll need an incremented number logic like:
var position_in_array = 0
var name = 'screenPopSettings'
object[`${position_in_array}${name}`] = value
position_in_array += 1
The parseJson returns data in object form and object doesn't has index. So we should define custom index of data array, if we want to keep the array index.
Example:
$arr[0] = array(
'Contact'=>array(
'key1'=>'val',
)
);
$arr[1] = array(
'Account'=>array(
'key1'=>'val',
)
);
It will produce the output as per the array index originally defined before parseJson function call.
I'm building an Angular App and also using angular translate as it needs to be in dual languages.
I've seem to have created my JSON properly (ran it through a checker), but when I try to access items within the JSON object beyond the first level, it returns undefined.
For instance, my JSON within the angular translations is this:
$translateProvider.translations('en', {
"SEARCH": {
"SEARCH" : "Recherce",
"ABILITY" : "Abilities",
"MANAGEMENT" : "Management Competencies",
"PERSONAL" : "Personal Suitability"
},
"ABILITIES": {
"TITLE" : "Test Title here",
"ADVISORY": {
"TITLE" : "Advisory Skills",
"QUESTIONS": [
{
"TYPE" : "A",
"LEVEL" : "45",
"DESCRIPTION" : "Can you tell me how awesome you are"
},
{
"TYPE" : "B",
"LEVEL" : "100",
"DESCRIPTION" : "Tell me about your wicked project"
}
]
}
},
"HEADLINE": "Oh No!",
"SUB_HEADLINE": "Looks like you are not amazing"
});
And to begin accessing the data in the JSON object, I do
list = $translateProvider.translations('en');
Now, when outputting items in the console to see if they work I do this:
console.log(list);
var getTitle = list.HEADLINE;
var getSearch = list.SEARCH.ABILITY;
console.log(getSearch);
console.log(getTitle);
This is where it gets odd.
The 'list' returns the JSON array I specified
Getting the HEADLINE returns Oh No!
But getting list.SEARCH.ABILITY returns an undefined
What gives!? I haven't event tried to access the stuff I really want in the really nested array "ABILITIES"
Keep in mind that Angular Translate uses the format {{ 'ABILITIES.ADVISORY.TITLE' | translate }} to output the JSON onto the HTML page
try list.SEARCH["ABILITY"].value
I serially collect information from forms into arrays like so:
list = {"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"};
identifier = "first_round";
list = {"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"};
identifier = "second_round";
I want to combine them into something (I may have braces where I need brackets) like:
list_all = {
"first_round" :
{"name" : "John", "email" : "name#domain.com", "country" : "Canada", "color" : "blue"} ,
"second_round" :
{"name" : "Harry", "email" : "othername#domain.com", "country" : "Germany"}
};
so I can access them like:
alert(list_all.first_round.name) -> John
(Note: the name-values ("name", "email", "color") in the two list-arrays are not quite the same, the number of items in each list-array is limited but not known in advance; I need to serially add only one array to the previous structure each round and there may be any number of rounds, i.e. "third-round" : {...}, "fourth-round" : {...} and so on.)
Ultimately, I'd like it to be well-parsed for JSON.
I use the jquery library, if that helps.
Create list_all as a new object as follows:
var list_all = {};
list_all[identifier_1] = list_1;
list_all[identifier_2] = list_2;
// ...
JSON uses object literal notation. The form:
var person = {
"name": "Douglas Adams"
"age": 42
};
Is exactly the same (for all intents and purposes) as:
var person = new Object();
person.name = "Douglas Adams";
person.age = 42;
Does that help you?
You can also use
person["age"]
this is the same as
person.age
and to iterate through named properties:
//prints the person.propertyName for all propertyName in person
for (var propertyName in person) {
alert(person[propertyName]);
}
You can transmit data as a string, using it to interact with the server and converting it into an object, using jQuery. Ex:
var jsonString = "{'name': 'Douglas Adams', 'age': 42}";
jQuery.parseJson(jsonString); //returns this as an object
Search for JSON in the jQuery API docs: http://api.jquery.com/