0

I have a two json objects

JSONObject org_query = new JSONObject("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");

JSONObject query_form = new JSONObject("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");

I want to append the second object to first one inside the key must and form a new JSON object.

Required Output:

{"query":{"bool":{"must_not":[],"should":[],"must":[{"match_phrase": {"Sales Channel": "Online"}}]}}}

I tried this,

org_query["query"]["bool"]["must"].append(query_form);

But shows error.

array type expected found org.json.jsonarray java

How to make it

2
  • What error? Your second json is not valid. Commented Feb 14, 2020 at 13:21
  • Looks like elasticsearch queries... Why not use their Java sdk? Commented Feb 14, 2020 at 15:18

3 Answers 3

1

In this case you can do:

org_query = org_query.put("query", org_query.getJSONObject("query").put("bool", org_query.getJSONObject("query").getJSONObject("bool").append("must", query_form)));
Sign up to request clarification or add additional context in comments.

Comments

0

Not really sure which API you're using but a quick search on Google yielded this result:

The .append method is for adding values into an array.

Try using .put method. This is for adding values to a property by key.

Reference: https://docs.oracle.com/middleware/maf242/mobile/api-ref/oracle/adfmf/json/JSONObject.html

For more examples, see this other answer: https://stackoverflow.com/a/30006004/7119882

1 Comment

Thanks... I found that... org_query.getJSONObject("query").getJSONObject("bool").getJSONArray("must").put(query_form);
0

You can use small json library

JsonValue org_query = JsonParser.parse("{\"query\": {\"bool\": {\"must\": [], \"must_not\": [], \"should\": []}}}");
JsonValue query_form = JsonParser.parse("{\"match_phrase\": {\"Sales Channel\": \"Online\"}}");
JsonValue must = org_query.findFirst(SPM.path("query", "bool", "must"));
must.asArray().add(query_form);
String result = org_query.toCompactString();

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.