6
$\begingroup$

Good day

I am trying to display my weather data in a JSON format in order to use it in an iOS app (using swift in Xcode). This is what my code looks like at the moment:

CloudDeploy[APIFunction[{"location" -> "Location"}, 
{temp : QuantityMagnitude[WeatherData[#location, "Temperature"]], 
hum : QuantityMagnitude[WeatherData[#location, "Humidity"]], 
windD : QuantityMagnitude[WeatherData[#location, "WindDirection"]], 
windS : QuantityMagnitude[WeatherData[#location, "WindSpeed"]]} &,
"JSON"], Permissions -> "Public"] 

This code produces the following output (after you put in "? location=Stellenbosch" at the end of the URL):

Failed to export to JSON for input:
{temp:21.4, hum:0.526, windD:320, windS:11.3} 

But if I change the output to "Text" then it gives the following output (after giving it a location parameter):

temp:21.4
hum:0.526
windD:320
windS:11.3

How do I get the weather data in a JSON format??

Thank you in advance

$\endgroup$
5
$\begingroup$

The : is used for named patterns, it's not part of any key-value data structure in Mathematica. You will not find it used in the way you propose anywhere in the documentation. You could use either a list of rules:

ExportString[{
  "key1" -> "value1",
  "key2" -> "value2"
  }, "JSON"]

"{ "key1": "value1", "key2": "value2" }"

Or an Association:

ExportString[<|
  "key1" -> "value1",
  "key2" -> "value2"
  |>, "JSON"]

"{ "key1": "value1", "key2": "value2" }"

I'm showing here that those data structures can be exported to JSON, you do not need to use ExportString, that's not the point.

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.