How to create JSON Object using String?
org.json.JSONArray
may be what you want.
String message;
JSONObject json = new JSONObject();
json.put("name", "student");
JSONArray array = new JSONArray();
JSONObject item = new JSONObject();
item.put("information", "test");
item.put("id", 3);
item.put("name", "course1");
array.put(item);
json.put("course", array);
message = json.toString();
// message
// {"course":[{"id":3,"information":"test","name":"course1"}],"name":"student"}
Create JSON object dynamically via JavaScript (Without concate strings)
This is what you need!
function onGeneratedRow(columnsResult)
{
var jsonData = {};
columnsResult.forEach(function(column)
{
var columnName = column.metadata.colName;
jsonData[columnName] = column.value;
});
viewData.employees.push(jsonData);
}
How to fluently build JSON in Java?
I am using the org.json library and found it to be nice and friendly.
Example:
String jsonString = new JSONObject()
.put("JSON1", "Hello World!")
.put("JSON2", "Hello my World!")
.put("JSON3", new JSONObject().put("key1", "value1"))
.toString();
System.out.println(jsonString);
OUTPUT:
{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}
How to dynamically build a JSON object?
You build the object before encoding it to a JSON string:
import json
data = {}
data['key'] = 'value'
json_data = json.dumps(data)
JSON is a serialization format, textual data representing a structure. It is not, itself, that structure.
Best way to create this JSON object in Golang
Declare types that match the structure of the JSON document.
type client struct {
Hostname string `json:"Hostname"`
IP string `json:"IP"`
MacAddr string `json:"MacAddr"`
}
type connection struct {
Clients []*client `json:"Clients"`
}
Initialize values using those types and encode to JSON.
var clients []*client
for _, line := range strings.Split(line, "\n") {
if line != "" {
s := strings.Split(line, " ")
clients = append(clients, &client{Hostname: s[0], IP: s[1], MacAddr: s[2]})
}
}
p, _ := json.Marshal(connection{Clients: clients})
fmt.Printf("%s\n", p)
The JSON field tags (json:"Hostname"
) are not needed in this example because the JSON object keys are valid exported identifiers. I include the tags here because they are often needed.
Run the code on the Go Playground.
How to create a JSON object in Ruby
The core of your problem is that you are creating an array of JSON strings, instead of an array and then making that JSON. Instead of:
companies_json = []
data_hash.each do |hash|
companies_json << hash.to_json
end
do:
companies = []
data_hash.each do |hash|
companies << hash
end
companies_json = companies.to_json
How can I build this JSON object in Flutter?
This part is not correct:
newQuiz = Quiz.fromJson(newQuestion.toJson());
Think about it, newQuestion.toJson()
will give you something like:
{
"question" : "La velocidad de la luz es igual a",
"solucion1": "300k",
"solucion2": "250k",
"solucion3" : "150k",
"answer" : "300k"
}
But Quiz.fromJson()
expects data to be in a format like this:
{
"questions": [
{
"question" : "La velocidad de la luz es igual a",
"solucion1": "300k",
"solucion2": "250k",
"solucion3" : "150k",
"answer" : "300k"
}
]
}
Maybe try:
newQuiz = Quiz(questions: [newQuestion, ...newQuiz.questions]);
Or even just this:
newQuiz.questions.add(newQuestion);
Build a JSON string with Bash variables
You are better off using a program like jq
to generate the JSON, if you don't know ahead of time if the contents of the variables are properly escaped for inclusion in JSON. Otherwise, you will just end up with invalid JSON for your trouble.
BUCKET_NAME=testbucket
OBJECT_NAME=testworkflow-2.0.1.jar
TARGET_LOCATION=/opt/test/testworkflow-2.0.1.jar
JSON_STRING=$( jq -n \
--arg bn "$BUCKET_NAME" \
--arg on "$OBJECT_NAME" \
--arg tl "$TARGET_LOCATION" \
'{bucketname: $bn, objectname: $on, targetlocation: $tl}' )
Conditionally create json object
You can write
client.post("/workout", {
userId: id,
title: title,
description: desc,
});
there's no need for the check. If desc
is undefined the key description
will be removed when stringified to JSON.
Related Topics
Using Ruby's Optionparser to Parse Sub-Commands
Redirect the "Puts" Command Output to a Log File
Can't Convert Fixnum to String During Rake Db:Create
How to Use Define_Method Inside Initialize()
How to Use "Gets" on a Rake Task
Cucumber, Capybara and Selenium - Submitting a Form Without a Button
Rubymine: Rails Server Launcher Wasn't Found in the Project
How to Remove 4 Byte Utf-8 Characters in Ruby
Prawn PDF Attachments in the Email
App Pushed to Heroku Still Shows Standard Index Page
How to Specify Post Params in a Rails Test
Code to Generate Gaussian (Normally Distributed) Random Numbers in Ruby
How to Delete All Contents of a Folder with Ruby-Rails
Puts Doesn't Print Stuff to Console
Should I Use Class Method or Instance Method, and Why
Ruby/Rails Using || to Determine Value, Using an Empty String Instead of a Nil Value