Handling of null in JSON sourced from webread
14 次查看(过去 30 天)
显示 更早的评论
I am attempting to import data contained in a JSON from a RESTful service which works fine using webread by itself, however some of the data cells contain JSON 'null' which seems to be either ignored or handled as an empty cell, which is then subsequently removed (both null and the cell containing it) and results in a mismatch of array sizes.
I wish to download said data and vertically concatenate the arrays containing data, but as their length is inconsistent due to the null values and MATLAB's handling of null values (discarding them) I cannot. The nature of the data means I cannot add these cells back with a NaN value to maintain array dimensions as the position of the null value is inconsistent.
Is there a way to change MATLAB's handling of null values in JSON files grabbed using webread?
- JSON does not support IEEE 754 NaN/inf values
- Apparently MATLAB doesn't understand the null value that JSON does support (I'd expect null to be translated to NaN, or supported natively).
Any other solution to this problem would also be welcome, but I believe the best way would be to change how webread deals with the nulls, but the documentation and support is limited, and the functions for grabbing and decoding the data are hidden (and not revealing when you open them).
采纳的回答
Ben
2016-8-29
3 个评论
Robert Snoeberger
2016-9-1
Section 9 of the RFC 7159 JSON standard says, "a JSON parser MAY accept non-JSON forms or extensions." So, matlab may accept the string '{"x":NaN}' if it is considered a non-JSON form or extension.
Guillaume
2016-9-1
Yes, it may accept non-JSON forms, but it definitively SHOULD NOT generate non-valid JSON.
As per section 10 in your link, " A JSON generator produces JSON text. The resulting text MUST strictly conform to the JSON grammar."
Something, that for some reason, I've got a hard time convincing mathworks of.
更多回答(1 个)
Guillaume
2016-8-26
Matlab does understand null, for example, in r2016a,
>>json = matlab.internal.webservices.fromJSON('{"values":[1, "2", null]}')
>>json.values
ans =
[1]
'2'
[]
correctly returns a cell array with 3 entries, the last one being empty.
The problem appears to be when the array exclusive contains numbers and null matlab converts it to a matrix, which of course has no concept of null values.
It's impossible to see the code used to parse the json (it's a mex file), but I assume it first read all the data as a cell array. Check if the cell array contains only numeric values and then use cell2mat to convert it into a matrix if it does. Unfortunately, isnumeric is true for empty arrays and cell2mat simply ignores empty values.
At present, short of writing your own decoder, there is no workaround. I'll submit a bug request to mathworks.
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 JSON Format 的更多信息
产品
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!