JSON root elements and encoding - javascript

I'm having a JSON deserialized from Java as follow:
Java
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO);
JSON
"accounts" : [ {
"name" : "1009427721",
"value" : 16850.79,
"children" : [ {
"name" : "BITCOIN EARNINGS",
"value" : 10734.24,
"children" : [ {
"name" : "2017",
"value" : 1037.82,
"children" : [ {
"name" : "07",
"value" : 518.91
} ]
} ]
}, ...
The deserialized Java POJO being:
public class GraphDTO {
private Set<Account> accounts = new HashSet<>();
public Set<Account> getAccounts() {
return accounts;
}
}
Questions
How can I remove "accounts" from the generated JSON (first line) ?
Injecting the JSON form into JavaScript, I'm getting an encoded form like:
var data = { "accounts" : [ { ...
How can I avoid this ?

I don't think it's possible to avoid the accounts, but you can do this:
jsonInString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO.getAccounts());
We're waiting your way to parse JSON in javascript...

Got it work as follow:
Applying the answer of Mohicane:
mapper.writerWithDefaultPrettyPrinter().writeValueAsString(graphDTO.getAccounts())
Injecting the JSON from Java to JavaScript (in a JSP) with:
var data = ${graphDTOJSON};
Many thanks!

Related

add to my nested json doesn't work correctly

I am trying to "ADD" a new key "resource1" to my below JSON.
I tried jsonFile["entry"][2] = "resource1" . This worked.
Now i want to add an object with "resourceType", "code", "subject"...... like how it is displayed for "resource" in my json below. How do i achieve this???
Like this --> jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"} ?????
Need help here
jsonFile:
{
"resourceType" : "Bundle",
"type" : "transaction",
"entry" : [
{
"fullUrl": "urn:uuid:patient",
"resource" : {
"resourceType" : "Patient",
"name" : [
{
"given": ["Lola"],
"family": "Tes"
}
]
},
"request" : {
"method" : "POST",
"url" : "Patient"
}
},
{
"resource" : {
"resourceType" : "Observation",
"code" : {
"coding" : [
{
"system": "http://loinc.org",
"code": "15074-8",
"display": "Glucose [Moles/volume] in Blood"
}
]
},
"subject": {
"type" : "Patient",
"reference" : "urn:uuid:patient"
},
"valueQuantity": {
"value": "5",
"unit": "mmol/l",
"system": "http://unitofmeasure.org",
"code": "mmol/L"
}
},
"request" : {
"method" : "POST"
}
}
]
}
Looks like you are trying to add the property to non existing object.
From your example.
jsonFile["entry"][2] = "resource1"
this worked because you are adding this to existing property(i.e. jsonFile has entry object which is array. So, it's just simply pushing this to array.
But when you are trying this,
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
it's trying to add property to non extsting object(i.e. jsonFile has entry, but entry has only 0 and 1 position objects in array. So, this will throw error.
To add property at 2nd position, you need to initialise object at that position and then you can add property.
You can do it in following ways,
jsonFile["entry"][2] = {}
jsonFile["entry"][2]["resource1"] = {"resourceType" : "Observation"}
Or
jsonFile["entry"][2] = {"resource1":{"resourceType" : "Observation"}}
You can add property to object if and only if that object is exists.

Modify existing json file using nodejs

I have a json file named a1.json->(It has the following structure)
{ "Key1" :
[ {
"Key11" : "Value11" ,
"Key12" : "Value12"
},
{
"Key21" : "Value21" ,
"Key22" : "Value22"
}
]
}
I am iterating through a data file which has certain values. If the values match i will have to add an extra key to that particular dictionary only. For example-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1"
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
I want to add a key value pair in that list whose key value "a" is "A1". So the final result will look something like this-
{ "Key1" :
[ {
"a" : "A1" ,
"b" : "B1" ,
"New_Key_Array" :
[
{
"Found" : "yes",
"Correctness" : "true"
}
]
},
{
"a" : "A2" ,
"b" : "B2"
}
]
}
How do I go about this. I am a bit new to JSON formatting and still learning how to edit existing JSON files?
You can use JSON.parse() to parse your json file/string into a JavaScript object. In your example:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
To add a new key to your object, it's possible with native JavaScript code, if that's what you want:
j.Key1[0]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
To convert back into json formatted string, you can use the JSON.stringify() function.
I am providing a code snippet for your problem:
let j = JSON.parse('{ "Key1" :[ { "a" : "A1" , "b" : "B1"},{"a" : "A2" , "b" : "B2"}]}');
console.log("JSON at the beginning:\n", j);
j.Key1.forEach((element, index) =>{
if(element.a === "A1"){
//Here I have to edit the JSON obj
j.Key1[index]["New_Key_Array"] = [ { Found: "yes", Correctness: "true" } ];
}
});
console.log("JSON edited:\n ",j);
let objString =JSON.stringify(j);

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

How to check if array contains a value in Javascript

I have a json object which has an array property 'partners' like below:
{
"_id" : ObjectId("578667b1bb14ca1c2773adaa"),
"customer" : null,
"created" : ISODate("2016-07-13T16:09:21.015+0000"),
"description" : "",
"subject" : "case 2",
"__v" : NumberInt(5),
"partners" : [
ObjectId("57857d93038aacd81ef3ad55"),
ObjectId("57857d93038aacd81ef3ad56")
]
}
I would like to check if an element already exists on the partner array using the following code:
_.includes(case_.partners, partner._id)
Just so u know I am using lodash for this but for some reason is not working and I have no clue why, anyone knows what is the problem here?
What I understanding, the partners sample you provided, is an javascript object, you should try to use primitive type value in the Json.
You can convert ObjectId to String by these way:
ObjectId("578667b1bb14ca1c2773adaa") + '';
or
ObjectId("578667b1bb14ca1c2773adaa").toHexString();
The Json object should be like this:
{
"_id" : "578667b1bb14ca1c2773adaa",
"customer" : null,
"created" : "2016-07-13T16:09:21.015+0000",
"description" : "",
"subject" : "case 2",
"__v" : 5,
"partners" : [
"57857d93038aacd81ef3ad55",
"57857d93038aacd81ef3ad56"
]}
So the solution will be , convert Javascript object into Json object, and then compare them.

How to access a part of a JSON file

Im trying to access some data and keep getting errors no matter what I try. Please help.
"rain":{"3h":13.625} is the part of the JSON file I am trying to access.
Here is what I have tried:
var currentRain = data.rain.3h; Which is most logical as it worked before but the number is what is giving the error.
var currentRain = data.rain["3h"];
var currentRain = data.rain[0]["3h"];
var currentRain = data.rain["3h"][0];
UPDATE:
This is the JSON payload:
{ "base" : "stations",
"clouds" : { "all" : 92 },
"cod" : 200,
"coord" : { "lat" : -33.850000000000001,
"lon" : 151.22
},
"dt" : 1429558616,
"id" : 6619279,
"main" : { "grnd_level" : 1024.97,
"humidity" : 100,
"pressure" : 1024.97,
"sea_level" : 1031.0999999999999,
"temp" : 288.77699999999999,
"temp_max" : 288.77699999999999,
"temp_min" : 288.77699999999999
},
"name" : "City of Sydney",
"rain" : { "3h" : 13.625 },
"sys" : { "country" : "AU",
"message" : 0.0101,
"sunrise" : 1429474880,
"sunset" : 1429514809
},
"weather" : [ { "description" : "heavy intensity rain",
"icon" : "10n",
"id" : 502,
"main" : "Rain"
} ],
"wind" : { "deg" : 157.5,
"speed" : 8.3200000000000003
}
}
You'll need to use ["bracket notation"] to access this, since "3h" begins with a number. As MDN explains:
An object property name can be any valid JavaScript string, or anything that can be converted to a string, including the empty string. However, any property name that is not a valid JavaScript identifier (for example, a property name that has a space or a hyphen, or that starts with a number) can only be accessed using the square bracket notation.
This is the correct JSON:
{
"rain": {
"3h": 13.625
}
}
First you need to parse it and transform into an object:
var jsonToObject = JSON.parse('{"rain":{"3h":13.625}}');
You can now access it like this:
jsonToObject.rain["3h"]
Just use data["rain"]. If you need to parse it first do JSON.parse(data) and then data["rain"].
OUTPUT
console.log(data["rain"]);
> { '3h': 13.625 }
...keep in mind that will return an Object.

Categories

Resources