I have a few data JSON files similar to this and I want to include a line to note the sources as simple as //source: Cambodia Department of Injustice but JSON files should contain only data.
Should should it be done?
If you can change the data structure slightly, you could add a level for metadata:
{
"metadata": {
"source": "Cambodia Department of Justice",
"source-date": "2015-12-15",
"note": "Ha ha made you look"
},
"countries": {
"USA": { some data }
"Canada": { Some data }
}
}
This is cleaner than use a fake "non-data" country.
Related
This question is purely syntax. I'm trying to insert a generated JSON object into another JSON object.
Let's say my JSON looks like this:
var database =
{
"john": {
"pwd": "somehashrighthere",
"mail": "example#gmail.com"
}
}
This object stores a hash and an email under the users name. Now I want to insert a new user:
var name = "somename";
var pwd = "hash";
var mail = "email#email.net";
If I try to insert this into a json object as by
database.name =
{
"pwd": pwd,
"mail": mail
}
I would expect an output that fills the gaps:
{
"john": {
"pwd": "r1pper",
"mail": "example#gmail.com"
},
"somenamerighthere": {
"pwd": "hash",
"mail": "email#email.net"
}
}
Instead the javascipt takes the expression quite literall:
{
"john": {
"pwd": "r1pper",
"mail": "example#gmail.com"
},
"name": {
"pwd": "pwd",
"mail": "mail"
}
}
I'm quite new to javascript/json and would appreciate if you guys exlain to me how one could dynamically(!) generate json objects and feed them into a bigger data structure. None of the answers I found on SO could solve this problem in a way I could understand. Do I need to make changes to the datastructure, or have I just misunderstood the javascript/node.js syntax. Thanks in advance :)
Edit: I solved the problem quite simply. Turns out javascript actually passes the variables into the json and I was just confused:
{
"john": {
"pwd": "r1pper",
"mail": "example#gmail.com"
},
"name": {
"pwd": "hash",
"mail": "email#email.net"
}
}
Now we just need to pass the name dynamically, which can be solved by treating the JSON, as if it was an array:
database[name]
treats name as a variable.
Edit 2:
The comments below came in while editing. I apologize for that.
you should use database[name] (take the value of name and use as index)
instead of database.name (use the string 'name' as index)
I am trying to display a tree structure in my web project.
I am using Symfony 3.4.x with jsTree v3.3.5.
PROBLEM
I can not get the tree to display when using json and ajax.
I am using an example from official jstree documentation.
If i hard code data in json format the tree is displayed without a hitch, but when i return the same json as part of ajax call - tree is not displayed (i get only one item, displayed as a folder, without a name).
I want to display all the tree nodes fully open - so loading all items is required.
CODE
my data in json format (i am using alternative json notation as per jstree documentation)
{"success":true,
"data":[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]}
using jstree
$(document).ready(function()
{
let project_tree;
project_tree = $('#file-tree-json');
project_tree.jstree({
'core':
{
'data':
{
'url': '/tree/prepare',
'dataType': 'json',
'data': function (node) {
console.log(node);
return { 'id': node.id };
},
}
},
"types": {
"root": {
"icon": "lnr lnr-home"
},
"folder": {
"icon": "lnr lnr-folder"
},
"file": {
"icon": "lnr lnr-file-empty"
}
},
"search": {
show_only_matches: true,
search_callback: function (str, node)
{
if (node.text.toLowerCase().indexOf(str) >= 0) { return true; }
}
},
"plugins": [ "types", "search" ]
});
}
code in my controller that prepares tree items data in json format
$em = $this->getDoctrine()->getManager();
$repo_file_tree = $em->getRepository('App:FileTree');
try
{
$build_my_tree_json = $repo_file_tree->prepareJsonTree($build_my_tree);
return new JsonResponse([
'success' => true,
'data' => $build_my_tree_json
]);
}
catch (\Exception $exception)
{
return new JsonResponse([
'success' => false,
'code' => $exception->getCode(),
'message' => $exception->getMessage(),
]);
}
Other discussions on SO that are related and which i already read, but in my opinion, they did not solve the problem at hand or/and refer to jstree version that is out of date
jsTree unable to load root nodes from AJAX call
jsTree - loading subnodes via ajax on demand
JSTree - Load nodes dynamically
JStree and ajax
https://stackoverflow.com/a/22965656
CONCLUSION
What am i doing wrong?
Maybe i am overlooking some detail or technicality?
Thank you for your comments and answers.
UPDATE 1
when i am returning only data
return new JsonResponse([
$build_my_tree_json
]);
i get additional "[]" as so
[[
{"id":"50","parent":"#","text":"test_root"},
{"id":"51","parent":"50","text":"test_1"},
{"id":"123","parent":"51","text":"test_2"},
{"id":"73","parent":"51","text":"test_3"},
{"id":"75","parent":"51","text":"test_4"},
{"id":"76","parent":"51","text":"test_5"},
{"id":"74","parent":"51","text":"test_6"},
{"id":"78","parent":"51","text":"test_7"},
{"id":"124","parent":"51","text":"test_8"},
{"id":"77","parent":"50","text":"test_9"}
]]
How can one remove extra "[]" from json or reference inner array?
UPDATE 2
it works when there are returned only data about tree nodes in json format.
working example
return new JsonResponse($build_my_tree_json);
So how to make jstree work with additional data in ajax response?
There should be a way to extract all the data about tree from response that contains status and data (response as displayed in my questions CODE section).
The structure of your JSON response doesn't work well with jsTree. jsTree expects an Array of nodes. Your output structure has an array inside the data object. You should have a structure as below in your response for it to work.
[
{
"id": "50",
"parent": "#",
"text": "test_root",
"opened":true
},
{
"id": "51",
"parent": "50",
"text": "test_1"
},
{
"id": "123",
"parent": "51",
"text": "test_2"
},
...
...
]
I have a json file that I want to use to load my Dynamo table in AWS.
In the AWS console, there is only an option to create one record at a time. Not good: )
Essentially my .JSON file is an array of objects which hold the data for each column in the table
ie:
{
"Column1": "Column1 Value",
"Column2": "Column2 Value",
"Column3": "Column3 Value",
"Column4": "Column4 Value",
},
Is there any way to do this via AWS console and importing my json file, or do I have to use AWS JS SDK to programmatically do this ??
The answer from E.J. Brennan looks correct, for a single record, but it doesn't answer the original question (which needs to add an array of records).
For this, the command is
aws dynamodb batch-write-item --request-items file://aws-requests.json
But, you'll need to make a modified JSON file, like so (note the DynamoDB JSON that specifies data types):
{
"YourTableName": [
{
"PutRequest": {
"Item": {
"Column1": { "S": "Column1 Value" },
"Column2": { "S": "Column2 Value" },
"Column3": { "S": "Column3 Value" },
"Column4": { "S": "Column4 Value" },
}
}
},
{
"PutRequest": {
"Item": {
"Column1": { "S": "Column1 Value" },
"Column2": { "S": "Column2 Value" },
"Column3": { "S": "Column3 Value" },
"Column4": { "S": "Column4 Value" },
}
}
}
]
}
You don't need to use the API. You could use the AWS-CLI instead, i.e:
aws dynamodb put-item --table-name MusicCollection --item file://item.json --return-consumed-capacity TOTAL
but you may need to tweak your JSON format a bit.
More examples and documentation here:
https://docs.aws.amazon.com/cli/latest/reference/dynamodb/put-item.html
I used boto3 in python to load the data
import boto3
import json
dynamodbclient=boto3.resource('dynamodb')
sample_table = dynamodbclient.Table('ec2metadata')
with open('/samplepath/spotec2interruptionevent.json', 'r') as myfile:
data=myfile.read()
# parse file
obj = json.loads(data)
#instance_id and cluster_id is the Key in dynamodb table
response=sample_table.put_item(
Item={
'instance_id': instanceId,
'cluster_id': clusterId,
'event':obj
}
)
Here is a sample for javascript:
https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/GettingStarted.Js.02.html#GettingStarted.Js.02.02
The code above doesn't read in individual JSON objects, if you wanted to do that from a JSON file with multiple objects:
import boto3
import json
dynamodbclient=boto3.resource('dynamodb')
sample_table = dynamodbclient.Table('ec2metadata')
with open('/samplepath/spotec2interruptionevent.json', 'r') as myfile:
data=myfile.read()
# parse file
objects = json.loads(data)
#instance_id and cluster_id is the Key in dynamodb table
for object in objects:
instance_id = object["instance_id"]
cluster_id = object["cluster_id"]
sample_table.put_item=(item=object)
This is my JSON Response of my Rest API.
{"ListClientResponse": {
"Header": {"CMMHeader": {"CorrelationId": "cmm:CorrelationId"}},
"Result": {
"ResponseCode": "CM-N-0000",
"ResponseMessage": "No errors and warnings."
},
"ListClient": {"Client": [
{
"OrganizationId": 523,
"OrganizationName": "OrgX1518521.com",
"OrganizationDomain": "X1518521.com"
],
"RoleId": "AdminRole",
"RoleName": "Admin"
}
},
I want to save Organization Id and OrganizationDomain from my JSON Response in a variables or something so that I can use these values later in my all JSON requests.
This is my JSON request.
var myCreateUserRequest = {
"CreateUserRequest": {
"Header": {
"CMMHeader": {
"CorrelationId": 5454354}},
"ClientContext": {
"OrganizationId": **theOrgId,**
"OrganizationDomain": **theDomain,**
},
"User": {
"UserName": aUser.Username,
"UserPassword": aUser.Password,
"UserStatus": "Active",
"RoleId": "Member"
}
}
}
In my JSON request, inside the field of OrganizationId and OrganizationDomain I want to pass that organizationID value and OrganizationDomain value that I have saved from my JSON Response in a varibale. I want to save it in a way so that organizationId and OrganizationDomain can be accessible in my whole ANGULAR JS project and I can pass it in my any JSON request. How can I do that. Please tell me any suggestion.
Best practice in this case tells to create a service. Becouse services are singleton in Angular, you can set a vale and inject in yours services/controllers and have access to the value.
I have a Firebase structure like below. I want to get the message as a returned object. To do this in SQL like
select messages from HukMesssage
How can I do that?
Can anyone helps me how to change the SQL to Firebase query?
My json file looks like below
{
"HukMessages":
[
{
"To": 1,
"From": 2,
"messages": [
{
"name": "'Venkman'",
"message": "'You on your way?'",
"face": "'img/venkman.jpg'"
},
{
"name": "'Felix He'",
"message": "'Ionic comes with a set of colors to start with, but as a general rule colors are meant to be overridden. '",
"face": "'img/felix.jpg'"
}
]
}
]
}
When you execute a query against the Firebase Database, there will potentially be multiple results. So the snapshot contains a list of those results. Even if there is only a single result, the snapshot will contain a list of one result.
Your code will need to deal with the list. Something like:
var query = firebase.database().ref().child("HukMessages").orderByChild("From").equalTo('2');
query.once("value", function(snapshot) {
console.log(snapshot.key); // this will print HukMessages, because that's the location you queried
snapshot.forEach(function(child) {
console.log(child.key); // this will print the key of a message
});
});