Ruby parse string to json - json

So I have some json that looks like this, which I got after taking it out of some other json by doing response.body.to_json:
{\n \"access_token\": \"<some_access_token>\",\n \"token_type\": \"Bearer\",\n \"expires_in\": 3600,\n \"id_token\": \<some_token>\"\n}\n"
I want to pull out the access_token, so I do
to_return = {token: responseJson[:access_token]}
but this gives me a
TypeError: no implicit conversion of Symbol into Integer
Why? How do I get my access token out? Why are there random backslashes everywhere?

to_json doesn't parse JSON - it does the complete opposite: it turns a ruby object into a string containing the JSON representation of that object is.
It's not clear from your question what response.body is. It could be a string, or depending on your http library it might have already been parsed for you.
If the latter then
response.body["access_token"]
Will be your token, if the former then try
JSON.parse(response.body)["access_token"]

Use with double quotes when calling access_token. Like below:
to_return = {token: responseJson["access_token"]}
Or backslashes are escaped delimiters and make sure you first parse JSON.

Related

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

How to include a JSON encoded object as string in another object which will also be encoded in string

Suppose you have the following JSON object:
{"name":"John Smith",
"jsonData": "{\"comment\":\"He said \\\"It will work\\\", and we are waiting.\"}"
}
The question is how to convert the above object to a string using say JavaScript JSON.stringify() and be able to save it in a text field in the DB and retrieve it later, parse it, and also part the inner encoded object jsonData?
The problem is faced in JavaScript and Java. For simplicity, I will reproduce the problem in JavaScript:
var jsonStr = `{"name":"John Smith",
"jsonData": "{\\\"comment\\\":\\\"He said \\\"It will work\\\", and we are waiting.\\\"}"
}`;
var obj = JSON.parse(jsonStr);
var comments = JSON.parse(obj.jsonData);
console.log(comments)
The above is failing with the error: Uncaught SyntaxError: Unexpected token I in JSON at position 21
And, I couldn't figure out how to include a quoted string in the inner encoded JSON string He said "It will work".
I want the solution in both Java and JavaScript.
Have you considered base64 encoding the JSON string?
Read more about base64 encoding objects here:
Base64 encode a javascript object

Calling an API returns expected JSONArray, found JSONObject

I'm calling an API from Go and trying to push json string data from another api call into it.
I can hand craft the calls using a payload like
payload := strings.NewReader('[{"value1":333, "value2":444}]'
and everything is happy.
I'm now trying to covert this to take the json string {"value1":333, "value2":444} as an input parameter of type string to a function, but when I try and use that as the payload, the api is responding with
expected type: JSONArray, found: JSONObject
I naively tried setting the input to the function as []string and appending the data to an array as the input, but then strings.NewReader complained that it was being fed an array.. which is was.
I'm at a loss to work out how to convert a string of json into a json array that the api will be happy with.
I tried just surrounding the string with [] but the compiler threw a fit about incorrect line termination.
Must have been doing something wrong with the string, surrounding the {} with [] let the function pass the data, but there must be a better way than this.
Any ideas, or am I making this harder than it should be?
You were on the right track with the brackets, but you actually need to append the characters to the string. For example:
str := `{"value1":333, "value2":444}`
str = "[" + str + "]"
// [{"value1":333, "value2":444}]
https://play.golang.org/p/rWHCLDCAngd
If you use brackets outside a string or rune literal, then it is parsed as Go language syntax.

Enumerating of JObject of NewtonSoft.Json loses '\' character in C#

I would like to parse json string using JObject.Parse() of NewtonSoft.Json. Assume that the json string is like this:
{"json":"{\"count\":\"123\"}"}
The result of jObject.First.ToString() is "json": "{\"count\":\"123\"}".
The result of jObject["json"].ToString() is {"count":"123"}. Enumerating gets the same result as this.
The testing code I used is like this.
[TestMethod()]
public void JsonParseTest()
{
var json = "{\"json\":\"{\\\"count\\\":\\\"123\\\"}\"}";
var jObject = JObject.Parse(json);
Console.WriteLine($"json : {json}");
Console.WriteLine($"jObject.First.ToString() : {jObject.First}");
Console.WriteLine($"jObject[\"json\"].ToString() : {jObject["json"]}");
}
We can see that enumerating of jObject will lose the character '\'. What is the problem? I would be appreciated for any suggestion :)
EDIT 1
The version of NewtonSoft is 12.0.3 released in 2019.11.09.
The parser isn't loosing anything. There is no literal \ in your example. The backslashes are purely part of the JSON syntax to escape the " inside the string vlue. The value of the key json is {"count":"123"}.
If you want to have backslashes in that value (however I don't see why you would want that), then you need add them, just like you added them in your C# string (C# and JSON happen to have the same escaping mechanism):
{"json":"{\\\"count\\\":\\\"123\\\"}"}
with leads to the C# code:
var json = "{\"json\":\"{\\\\\\\"count\\\\\\\":\\\\\\\"123\\\\\\\"}\"}";

JSON Object Parse

exercise question screenshot
Not sure what's missing. The other discussion solutions seem too complicated compared to my homework question:
Q:
-The variable str_json has been assigned a string of a JSON object
-Call the parse method, pass it str_json and assign the return value to variable jsonobj
-Assign the property the_city to the variable v_the_city
-Assign the property stateval to the variable v_stateval
var str_json = {'v_the_city':'the_city','v_stateval':'stateval'};
var jsonobj = JSON.parse(str_json);
SyntaxError:
the JSON dataJSON.parse: unexpected character at line 1 column 2 of
SyntaxError: unexpected token: identifier
str_json should be a JSON string, not an object.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned. Read more here, link.
Syntax:
JSON.parse(text[, reviver])
Parameters:
text - The string to parse as JSON. See the JSON object for a description of JSON syntax.
reviver - [Optional] If a function, this prescribes how the value originally produced by parsing is transformed, before being returned.