Is it possible to wrap json in json field like a string? - json

I have a json like this:
json1 :
{
"field1": 111111,
"field2": "someValue"
}
How can I wrap it in "requestBody" field into json2 like a string?
json2 :
{
"requestBody": json1
}
Something like this:
{
"requestBody": "{"field1": 111111,"field2": "someValue"}"
}

JSON-encoded stuff is just a string. If you want to embed json-in-json, then the "inner" json has to be encoded into json itself.
e.g.
$inner = {"foo":"bar"}
$outer = {"container":"{\"foo\":\"bar\"}"}
Now the inner json isn't json anymore. It's just a string that happens to kinda/sorta look like JSON.

It won't be pretty, but if you base64 encode the JSON payload, you can be sure it won't be parsed unexpectedly.
How to base64 encode using Javascript:
http://www.webtoolkit.info/javascript-base64.html
{
"requestBody": "eyJmaWVsZDEiOiAxMTExMTEsImZpZWxkMiI6ICJzb21lVmFsdWUifQ=="
}

As Marc B noted, inner quotes must be escaped.
{"requestBody":"{\"field1\":111111,\"field2\":\"someValue\"}"}
Fiddle:
http://jsfiddle.net/cheoc1zj/

Escaping double quoted strings is ugly. Why not use single quoted strings in the embedded JSON? For example:
{
"container":"{'foo':'bar'}"
}

Related

Kotlin: JSON string with linebreaker and variable

I would like to add linebreakers to a JSON string so it will be more readable.
val myString = "some string"
val myObjectJson = `
{
"example1": "value",
"example2": $myString
}`
So later I can use ObjectMapper to create an object. objectMapper.readValue(myObjectJson, MyClass::class.Java)
What I'm trying to figure out:
How to add lineBreaker in Json string?
Tried template literals:"`", doesn't seem to work in Kotline. gives Expecting an expression error.
How to use variable in Json string?
This might go away after I figure out how to add linebreakers.
(Edited because I think I have misunderstood your question).
Are you asking how to lay out a JSON string in the source code? If so then what you are looking for is the Raw String feature implemented with 3 double-quotes like this:
val myObjectJson = """
{
"example1": "value",
"example2": $myString
}
"""
But in case you asking
How to add lineBreaker in Json string?
(Assuming you are using Jackson's ObjectMapper)
Simply use writerWithDefaultPrettyPrinter() like this: MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(value)
If that is not good enough for you I suppose you could implement a custom Pretty Printer: https://www.javadoc.io/static/com.fasterxml.jackson.core/jackson-core/2.14.2/com/fasterxml/jackson/core/PrettyPrinter.html

JSONPath: Get field starting with # in escaped json string

I want to get a nested field in a json string using JSONPath.
Take for example the following json:
{
"ID": "2ac464eb-352f-4e36-8b9f-950a24bb9586",
"PAYLOAD": "{\"#type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
}
If I want to extract the #type field, I expect to do it like this
$.PAYLOAD.#type
But that doesn't seem to work..
Also tried this:
$.PAYLOAD['#type']
Do I need to use escape chars or something?
Posting my comment as an answer
"{\"#type\":\"Event\",\"id\":\"baf223c4-4264-415a-8de5-61c9c709c0d2\"}"
Isn't JSON, it's a string containing encoded JSON.
Since JsonPath can't decode such string, you'll have to use a language of your desire to decode the string.
Eg: Decoding JSON String in Java

Escape dots in Groovy GPath

I am using the RestAssured framework in Java, whose documentation contains this note
Note that the "json path" syntax uses Groovy's GPath notation and is not to be confused with Jayway's JsonPath syntax.
I need to validate the following JSON:
"_source": {
"logSource": {
"logger.name": "LogbackLogger",
},
}
And the selectors like
_source.logSource.logger.name or
_source.logSource.logger.name[0] return no result.
I assume this is due to the dot in the logger.name property.
If no escaping is done, logger.name is interpreted as if name was under the logger, which is not true.
How do I correctly escape the dot character in the GPath, so that logger.name is considered as a single property name?
Thanks!
You have a trivial issue.
Just wrap it in between single quote i.e., 'logger.name'
as there is special character.
Here is complete example :
def string = """{ "_source": {
"logSource": {
"logger.name": "LogbackLogger",
}
}
}"""
def json = new groovy.json.JsonSlurper().parseText(string)
println json.'_source'.logSource.'logger.name'

Escaping JSON Payload with back slash

I have an external service that returns a JSON Payload as below
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
How could I escape the back slash? I need to use a json path and currently I cant do it. Is there a better way than String Replace? Thanks.
Regards,
Hari
Just simply parse your JSON string. like that.
var response = {
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
};
var result = $.parseJSON(response.GetIPAResult);
Now you can get your data (in result variable) without back slash.
hari .. at a moment your json structure are as follows
{"key": "value"}
where value is a stringify of {"Data" : JSONARRAY}
here 2 case arise..
case 1:
try to change the structure of return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
case 2:
try to convert return json to
{"key": JSONOBJECT}
where JSONOBJECT -> {"DATA": JSONARRAY}
by replace "{ with { , \" with " and }" with }
hence the result of
{
"GetIPAResult": "{\"Data\":[{\"Name\":\"Pan1\",\"Email\":\"abc#example.com\"},{\"Name\":\"Pan2\",\"Email\":\"xyz#example.com\"}]}"
}
to
{
"GetIPAResult": {"Data":[{"Name":"Pan1","Email":"abc#example.com"},{"Name":"Pan2","Email":"xyz#example.com"}]}
}

Convert String to JSON String in Swift

How can I convert string with format like:
{Param1: "Value", Param2: "value2", Param3: "value3"}
to JSON string for my Post query?
Thanks in advance.
This is already a JSON string just send it appended with the headers.
If you need to access these values, then you need to use something like swiftyJSON or JSONswift.
What you have posted appears to be a JSON string containing a dictionary.