Is this a correct JSON string? - javascript

I am not quite clear on how to make a JSON string. I get error and I want to find out how to correct and it make it.
This is my JSON string:
var drivers = { "driver" : [
{
"id" : 1,
"name" : "Bob",
"age" : "34"
"car" : [
{
"make" : "BMW",
"model" : "3.20",
"colour" : "Silver"
}
]
},
{
"id" : 2,
"name" : "Rob",
"age" : "22"
"car" : [
{
"make" : "Peugeot",
"model" : "306",
"colour" : "Blue"
}
]
},
{
"id" : 3,
"name" : "Maria",
"age" : "23",
"car" : [
{
"make" : "Mazda",
"model" : "3",
"colour" : "Red"
}
]
}]};
This is the get method:
var driverData = JSON.parse(drivers);
function getDriverData() {
return driverData;
}
return {
getDriverData: getDriverData
};
And in this controller I try to get it so I can see if it works:
var drivers = myDriveApi.getDriverData();
console.log(driverData);
Correct me and explain how to make a JSON string, and I want it nested if that's the right term. So each driver has a car, or multiple cars/vehicles. So if I get 1 driver, I want to see his details and his information on owned vehicles.

Your "JSON string" seems to be JavaScript code that you would have in a script tag that creates a drivers JavaScript object with a property called driver that is an array of other objects. To be JSON, you remove the var drivers = and the semicolon at the end leaving just what you would set a variable to in order to create that object.
For instance, let's say you have a "person" variable that is an object with "firstName" and "lastName" properties. This is code you would put into a script to create that variable:
var person = { firstName: "Jason", lastName: "Goemaat" };
Strings, even JSON strings are represented in scripts surrounded by single or double quotes. To see the string value for the JSON of that object, you can do this:
var json = JSON.stringify(person);
This gives you a valid JSON string which will display this in the console:
{"firstName":"Jason","lastName":"Goemaat"}
To set the variable directly you need to enclose it in single or double quotes, but if the string contains those they would need to be escaped. Since this contains only double quotes I will surround it in single quotes to assign it to a variable in my script, then parse that into an object.
var json = '{"firstName":"Jason","lastName":"Goemaat"}';
var person = JSON.parse(json);
JSON property names need to be surrounded in quotes. Most parsers will work if they are not but it is always better to be as correct as you can be. You can use the online tool at jsonlint to check for valid JSON.

No, that's a JavaScript object, which could be converted to a JSON string using JSON.stringify(object).
If you're trying to access it through JavaScript, you might as well skip JSON altogether and just use the object. If you want to test if a JSON string is good, use jsonlint.com.

It's a JavaScript object, not a JSON string.
You're missing commas after Bob and Rob's age. Maria's all good, though.

Related

How to split a JSON lookalike string and display it on vue.js

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}]`));

mongoDB: get field value of an array object

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});

Keep order of objects inside a JSON String after they are parsed

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.

Accessing nested JSON objects

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

merging javascript arrays for json

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/

Categories

Resources