How to Dynamically Build a Json Object

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

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
jsonObj = [];
$("input[class=email]").each(function() {

var id = $(this).attr("title");
var email = $(this).val();

item = {}
item ["title"] = id;
item ["email"] = email;

jsonObj.push(item);
});

console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

Create JSON object dynamically

Try constructing your JSON data as a string:

String json = "{" +
"\"tableID\": 1," +
"\"price\": 53," +
"\"payment\": \"cash\"," +
"\"quantity\": 3," +
"\"products\": [";

for (int i = 0; i < 100; i++) {
json += "{ \"ID\": 3, \"quantity\": 2 }";
if(i != 100) json += ",";
}

json += "]}";

and then create your JSONObject:

JSONObject jsonObject = new JSONObject(json);

I do not know what you exactly want to do, but I am guessing it is something like below:

for(int i = 0; i < products.size(); i++) {
json += "{" +
"\"ID\": " + products.get(i).getId() + "," +
"\"quantity\": " + products.get(i).getQuantity() + " }";
if(i != products.size() - 1) json += ",";
}

Note: See kws's answer for a more readable way to do it.

Dynamically build JSON in Python

You can create a helper function to dynamically populate the values in a dict object with the necessary structure:

from __future__ import annotations


def build_api_request(names: list[str],
first: str, last: str,
email: str,
mobile_no: str,
country_code: str | int):
return {
"list_name": ','.join(names),
"subscriptions": [
{"first_name": first,
"last_name": last,
"email": email,
"mobile": {"number": mobile_no,
"country_code": str(country_code)}}
]
}


req = build_api_request(["listname0001", "listname0002", "listname0003"],
"Subscriber's First Name",
"Subscriber's Last Name",
"subscriber_email0001@api.trumpia.com",
"2003004000",
1)

import json
print(json.dumps(req, indent=2))

Prints:

{
"list_name": "listname0001,listname0002,listname0003",
"subscriptions": [
{
"first_name": "Subscriber's First Name",
"last_name": "Subscriber's Last Name",
"email": "subscriber_email0001@api.trumpia.com",
"mobile": {
"number": "2003004000",
"country_code": "1"
}
}
]
}

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.

Create dynamic json object in python

In Python dictionaries you can't have 2 values with the same key. So you can't have multiple targets all called "target". So you can index them. Also I don't know what this question has to do with dynamic objects but here's the code I got working:

import re
dict_res = {}
ind = 0
for image in image_dict:
lin_ind = 0
sub_dict = {'image' + str(ind): {'imageId': {image}, 'link': {}}}
for sub in image_dict[image].values():
sub_dict['image' + str(ind)]['link'].update({'target' + str(lin_ind): {'id': sub}})
lin_ind += 1
dict_res.update(sub_dict)
ind += 1
dict_res = re.sub('target\d', 'target', re.sub('image\d', 'image', str(dict_res)))
print dict_res

Build dynamic JSON

Here is improved code from previous example that is more flexible and has better serialization mechanism :

public class ForTestApplication {

public static void main(String[] args) {

NodeArray jsonContainer = new NodeArray(
new Node("nodes", new NodeArray(
new Node("12131231231231241", new NodeArray(
new Node("gToken",
new Node("token", "AABBCCDDEEFF99001122334455667788")),
new Node("objects", new NodeArray(
new Node("WATER_CONTROL_1", "0"),
new Node("WATER_CONTROL_2", "1")
)))),
new Node("7682642342432423", new NodeArray(
new Node("userAuthentication", new NodeArray(
new Node("userEmail","user@mail.com"),
new Node("userPassword","userPassword")
)),
new Node("objects", new NodeArray(
new Node("WATER_CONTROL_1", "0"),
new Node("WATER_CONTROL_2", "1")
))
))
)));

System.out.println(jsonContainer.toJSONString());
}

}

class NodeArray {
private static final String NODE_TEMPLATE = "\"%s\":%s";
private static final Gson gson = new Gson();

private List<Node> nodes = new ArrayList<>();

public NodeArray(Node... nodes){
addNode(nodes);
}

public void addNode(Node... node){
nodes.addAll(Arrays.asList(node));
}

public String toJSONString() {

return nodes.stream()
.map(node -> String.format(NODE_TEMPLATE, node.getNodeName(), getNodeBodyAsJSON(node)))
.collect(Collectors.joining(",", "{", "}"));
}

private String getNodeBodyAsJSON(Node node) {
if (node.getNodeBody() instanceof NodeArray) {
return ((NodeArray) node.getNodeBody()).toJSONString();
}
return gson.toJson(node.getNodeBody());
}

}

class Node {
private final String nodeName;
private final Object nodeBody;

public Node(String nodeName, Object nodeBody) {
this.nodeName = nodeName;
this.nodeBody = nodeBody;
}

public String getNodeName() {
return nodeName;
}

public Object getNodeBody() {
return nodeBody;
}
}

The output of such application is :

{"nodes":{"12131231231231241":{"gToken":{"nodeName":"token","nodeBody":"AABBCCDDEEFF99001122334455667788"},"objects":{"WATER_CONTROL_1":"0","WATER_CONTROL_2":"1"}},"7682642342432423":{"userAuthentication":{"userEmail":"user@mail.com","userPassword":"userPassword"},"objects":{"WATER_CONTROL_1":"0","WATER_CONTROL_2":"1"}}}}

Pretty view is :enter image description here

NOTICE : this example use constructors to build complex structures but I highly recommend to use builder pattern for such case. Code will be clearer and better.



Related Topics



Leave a reply



Submit