I tried to parse a simple JSON like that:
JSON.parse({"pong": "ok"})
and it failed
2.4.0 :014 > JSON.parse({"pong": "ok"})
TypeError: no implicit conversion of Hash into String
from (irb):14
What's wrong here ? Why should I convert to String ?
Another try, with OpenStruct this time:
2.4.0 :001 > pong = OpenStruct.new(pong: 'OK')
=> #<OpenStruct pong="OK">
2.4.0 :002 > JSON.parse(pong)
TypeError: no implicit conversion of OpenStruct into String
from (irb):2
The same ?
Thank you
JSON.parse parses json and json means String:
JSON.parse('{"pong": "ok"}')
#⇒ {"pong"=>"ok"}
Also, you might parse json string into OpenStruct:
JSON.parse('{"pong":"ok"}', object_class: OpenStruct).pong
#⇒ "ok"
Related
i try to construct JSON with string that contains "\n" in it like this :
ver_str= 'Package ID: version_1234\nBuild\nnumber: 154\nBuilt\n'
proj_ver_str = 'Version_123'
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
json_content = json.loads()
d =json.dumps(json_content )
getting this error:
exec(compile(contents+"\n", file, 'exec'), glob, loc)
File "C:/Dev/python/new_tester/simple_main.py", line 18, in <module>
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
KeyError: '"r_content"'
The error arises not because of newlines in your values, but because of { and } characters in your format string other than the placeholders {0} and {1}. If you want to have an actual { or a } character in your string, double them.
Try replacing the line
comb = '{"r_content": {0}, "s_version": {1}}'.format(ver_str,proj_ver_str)
with
comb = '{{"r_content": {0}, "s_version": {1}}}'.format(ver_str,proj_ver_str)
However, this will give you a different error on the next line, loads() missing 1 required positional argument: 's'. This is because you presumably forgot to pass comb to json.loads().
Replacing json.loads() with json.loads(comb) gives you another error: json.decoder.JSONDecodeError: Expecting value: line 1 column 15 (char 14). This tells you that you've given json.loads malformed JSON to parse. If you print out the value of comb, you see the following:
{"r_content": Package ID: version_1234
Build
number: 154
Built
, "s_version": Version_123}
This isn't valid JSON, because the string values aren't surrounded by quotes. So a JSON parsing error is to be expected.
At this point, let's take a look at what your code is doing and what you seem to want it to do. It seems you want to construct a JSON string from your data, but your code puts together a JSON string from your data, parses it to a dict and then formats it back as a JSON string.
If you want to create a JSON string from your data, it's far simpler to create a dict with your values and use json.dumps on that:
d = json.dumps({"r_content": ver_str, "s_version": proj_ver_str})
I am making use of non-static import
JsonPath jp = response.jsonPath();
System.out.println(jp.get("data?(#.id>14).employee_name").toString());
For a JSON as shown below:
{"status":"success","data":[{"id":"1","employee_name":"Tiger Nixon","employee_salary":"320800","employee_age":"61","profile_image":""},{"id":"2","employee_name":"Garrett Winters","employee_salary":"170750","employee_age":"63","profile_image":""}]}
When i am trying to run it , i am getting below error:
java.lang.IllegalArgumentException: Invalid JSON expression:
Script1.groovy: 1: expecting EOF, found '[' # line 1, column 31.
data[?(#.id>14)].employee_name
^
1 error
Can someone guide me why is this error being thrown ?
I doubt if that syntax is right, nonetheless, you should be using the below
Also note that the id is a string in your response so you will have to include it in quotes
js.get("data.find {it.id > '14'}.employee_name").toString();
I have a json string like this :
{"weight": 56.}
I can enter this string into NodeJS interpreter and get a parsed hash as a result:
$ js
> {"Weight":56.}
{ Weight: 56 }
> {"Weight":56}
{ Weight: 56 }
as you see, NodeJS accepts both inputs with identical result
But in Ruby, for the same string I get
JSON::ParserError: ... unexpected token
until I remove '.' after the number
sample session :
irb...> s='{"Weight":56.}'
=> "{\"Weight\":56.}"
irb...> JSON.parse(s)
JSON::ParserError: 784: unexpected token at '{"Weight":56.}'
...
irb...> s='{"Weight":56}'
=> "{\"Weight\":56}"
irb...> JSON.parse(s)
=> {"Weight"=>56}
Can anything be done to Ruby JSON library to improve its conformance to JS ?
Now I have to filter these stray dec.points by regular expressions before parsing them as JSON
I use rest API on Ruby with sinatra.
I got payment information from IAMPORT,,,
def get_authrestapi()
#key = IMP_KEY
#secret = IMP_SECRET
response = RestClient.post 'https://api.iamport.kr/users/getToken', {'imp_key' => #key, 'imp_secret' => #secret}, :accept => :json
json = JSON.parse(response.to_json, symbolize_names: true)
return json['response']['access_token']
end
but, I got error message... like below
JSON::ParserError at /payments 757: unexpected token at '"{\"code\":0,\"message\":null,\"response\":{\"access_token\":\"9898....", "..."}}"'
How can I solve this problem?? I think,, there is problem that variable 'json' is not HASH..
Thanks.
Don't convert the response to json. It's already json.
Replace the following line:
json = JSON.parse(response.to_json, symbolize_names: true)
with:
json = JSON.parse(response, symbolize_names: true)
I have this JSON text:
data = {"one":"number","two":"string","three":"number","four":[{"five":"number","six","string"},{"five":"number","six":"string"}]}
How I can get "five"'s number and "six"'s string using Python 3.3 and using json module ?
P.S.: If I do print data['five'] it doesn't works with this error:
print(data['five'])
KeyError: 'five'
Thanks,
Marco
Try this:
data = {"one":"number","two":"string","three":"number","four":[{"five":"number","six":"string"},{"five":"number","six":"string"}]}
print(data['four'][0]['five']) # number
print(data['four'][0]['six']) # string