JSON Object Parse - json

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.

Related

Dynamic deserialize JSON from method

How to dynamic deserialize JSON from method in controller? I use that code:
dynamic dynJson = JsonConvert.DeserializeObject(GetReservedDaysJson().ToString());
And have that error:
Newtonsoft.Json.JsonReaderException: 'Unexpected character encountered while parsing value: M. Path '', line 0, position 0.'
My JSON from GetReservedDaysJson() function look like that:
["2022-03-29","2022-03-30"]
Unless someone has a better solution. It needs to compare each date with JSON. With the date provided in the model.
you can try this
string json = GetReservedDaysJson();
List<DateTime> dates = JsonConvert.DeserializeObject<List<DateTime>>(json);

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.

com.jayway.jsonpath.JsonPath cannot find key

I am trying to use com.jayway.jsonpath.JsonPath to read key/values from a JSON string:
String contentAsString = mvcResult.getResponse().getContentAsString();
System.out.println(contentAsString);
Object value = JsonPath.read(contentAsString, "$.key");
But I get the error:
Expected to find an object with property ['key'] in path $ but found 'net.minidev.json.JSONArray'. This is not a json object according to the JsonProvider: 'com.jayway.jsonpath.spi.json.JsonSmartJsonProvider'.
Printing contentAsString gives:
[{"firstName":"N","key":"mykey"}]
Is contentAsString not valid JSON?
The blob that you posted is not a valid JSON Object, however, it IS a valid JSON Array.
To read this using JsonPath, try using this:
Object value = JsonPath.read(contentAsString, "$[0].key");
This will get the value of the key object, from the 0th element of the initial array.

Ruby parse string to 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.

Jettison can not convert json string to json object when there is an element has empty string value

My application is using camel rest (2.15.2) to catch a POST json String and then uses jettison to convert to a JSON Object. It is working fine with normal request.
POST request: {"request"={"lname"="aaa", "fname"="bb"}}
1. String body = exchange.getIn().getBody(String.class);
2. JSONObject obj = new JSONObject(body);
When i debug, variable body = {request={lname=aaa, fname=bb}}.
And line 2 returns a JSONObject. so far so good
if we try to another the request:
{"request"={"lname"=" ", "fname"="aa"}}
then body = {request={lname= , fname=aa}}
line2 returns Exception.
Could you please help me to fix this issue: convert json string which contains element has empty value string to json object.
The above request is acceptable in my scenarios.
Error:
org.codehaus.jettison.json.JSONException: Missing value. at character
15 of {request={lname= , fname=aa}} at
org.codehaus.jettison.json.JSONTokener.syntaxError(JSONTokener.java:463)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:356)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at
org.codehaus.jettison.json.JSONTokener.newJSONObject(JSONTokener.java:412)
at
org.codehaus.jettison.json.JSONTokener.nextValue(JSONTokener.java:327)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:230)
at org.codehaus.jettison.json.JSONObject.(JSONObject.java:311)