Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 17 days ago.
The community reviewed whether to reopen this question 17 days ago and left it closed:
Original close reason(s) were not resolved
Improve this question
I have a JSON response in the following format:
{
"coordinates": [
"-0.88676",
"51.47533"
],
[
"-0.88646",
"51.47549"
]
}
I am struggling to parse this data and append each coordinates value into an array.
I can see that this is a dictionary array but if I try to parse as a dictionary I get an error. Parsing as an array returns just the one item which essentially is the json as a single entry.
I am not adding any of my code as I believe this would be fruitless, because I have been unable to achieve what I need without errors, and have tried numerous options, all without success.
At the moment your JSON is not valid JSON data. But that might be a typo.
If we change this into valid JSON...
{
"coordinates": [
[
"-0.88676",
"51.47533"
],
[
"-0.88646",
"51.47549"
]
]
}
Then you could represent this as a struct like...
struct Response: Decodable {
let coordinates: [[String]] // <- this is a 2D array of coordinate pairs.
var locations: [CLLocation2D] {
coordinates
.map { $0.compactMap(Double.init) }
.filter { $0.count < 2 }
.map { ($0[0], $0[1]) }
.map(CLLocation2D.init(latitude:longitude:))
} // Something like that anyway
}
Then you can decode it like...
let data = // get the data from the network or a file etc...
let response = JSONDecoder().decode(Response.self, from: data)
That should give you the struct you want.
Related
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I'm stuck on decoding a JSON in swift.
I've got the following code in a playground with a JSON that has 10 fields. When i try to decode the data I get the following Error
error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).
The process has been left at the point where it was interrupted, use "thread return -x" to return to the state before expression evaluation.
But this error does not seem to happen if I take out e.g. "ninth" and "tenth" or 2 of any of the other fields so only 8 fields remain in the struct.
Is there a limitation of only be able to have 8 fields decoded? Am I missing something?
is there anything i can do to overcome this issue?
My code snippet:
let decoder = JSONDecoder()
struct Positions: Codable {
let first : String
let second: String
let third: String
let forth: String
let fith: String
let sixth: String
let seventh: String
let eigth: String
let nineth: String
let tenth: String
}
var positions = """
{
"first" : "first",
"second": "second",
"third": "third",
"forth": "forth",
"fith": "fith",
"sixth": "sixth",
"seventh": "seventh",
"eigth": "eigth",
"nineth": "nineth",
"tenth": "tenth"
}
""".data(using: .utf8)
let result = try decoder.decode(Positions.self, from: positions!)
print("tr \(result)")
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I've got a JSON file called 'books.json' looking like this:
{"Books":
[
]
}
and I'd like to add something like this into the array using Go:
{
"Title": "Lord of the Rings",
"Author: "J. R. Tolkien",
"Language: "English"
}
Create a struct to hold your data:
type Book struct {
Title string `json:"Title"`
Author string `json:"Author"`
Language string `json:"Language"`
}
type Library struct {
Books []Book `json:"Books"`
}
Unmarshal existing JSON to the struct:
in := `{"Books": []}`
var library Library
json.Unmarshal([]byte(in), &library)
Append a new Book:
newBook := Book{
Title: "Lord of the Rings",
Author: "J.R. Tolkien",
Language: "English",
}
library.Books = append(library.Books, newBook)
Marshal back to JSON and check the result:
j, _ := json.Marshal(library)
fmt.Println(string(j))
Entire code on Go Playground: https://play.golang.org/p/v24dKorFpK5
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I am receiving JSON text, converting it to Data, and then using JSONDecoder to create a concrete type represented by the JSON text/string.
It does work with my "complex" data structure (which implements Codable), or even a simple array of Int as shown below:
import Foundation
let jsonTextContainigArrayOfInt: String = "[1,2,3]"
let data = jsonTextContainigArrayOfInt.data(using: .utf8)!
do {
let arrayOfInt: [Int] = try JSONDecoder().decode([Int].self, from: data)
for n in arrayOfInt {
print(n)
}
}
catch {
print(error)
}
The previous code works and correctly creates the array of Int and prints them.
The problem occurs when doing this same approach with a single Int in the JSON-text:
import Foundation
let jsonTextContainigOneInt: String = "1"
let data = jsonTextContainigOneInt.data(using: .utf8)!
do {
let myInt: Int = try JSONDecoder().decode(Int.self, from: data)
print(myInt)
}
catch {
print(error)
}
For this second approach, I get the following error:
"The operation could not be completed"
*** Edit ***
Bug report for this already exists: https://bugs.swift.org/browse/SR-6163
JSONDecoder can only decode a collection type (array or dictionary) as root object.
Under the hood JSONDecoder uses JSONSerialization without any options. However to decode a String or Int you have to specify the .allowFragments option.
Use JSONSerialization with the .allowFragments option
let jsonTextContainingOneString = "1"
let data = Data(jsonTextContainingOneString.utf8)
do {
let myString = try JSONSerialization.jsonObject(with: data, options: .allowFragments)
print(myString)
}
catch {
print(error)
}
Interesting... I found this:
https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/JSONSerialization.swift#L120
Specifically this guard statement:
open class JSONSerialization : NSObject {
//...
// top level object must be an Swift.Array or Swift.Dictionary
guard obj is [Any?] || obj is [String: Any?] else {
return false
}
//...
}
Then I looked if a simple text-string should be considered valid JSON, and apparently it should now (it was previously not accepted as valid JSON). At least, based on this excellent answer: https://stackoverflow.com/a/7487892/8284660
This makes me wonder whether or not the behavior on my original post should be a bug or not.
This question already has answers here:
Unmarshal 2 different structs in a slice
(3 answers)
Closed 4 years ago.
How would I deserialize this JSON in Go?
{
"using": [ "jmap-core", "jmap-mail" ],
"methodCalls": [
["method1", {"arg1": "arg1data", "arg2": "arg2data"}, "#1"],
["method2", {"arg1": "arg1data"}, "#2"],
["method3", {}, "#3"]
]
}
I haven't figured out how to properly get the json module to parse the methodCalls into a type. My first idea was
type MethodCall struct {
Name string
Params map[string]string
ClientId string
}
and then to use it as a list type:
type Request struct {
Using []string
MethodCalls []MethodCall
}
But this does not work. :using" is correctly parsed, but the "methocCalls" are not. Is there a way to get Go to parse this JSON into my types?
It looks like the methodCalls that you are trying to deserialize it is an array of strings instead of a struct for MethodCall.
So, Take a look at this link that I am deserializing as an array.
If you want to use the MethodCall struct you have to change the json a little bit. Take a look at this link
This question already exists:
Closed 10 years ago.
Possible Duplicate:
How to extract specific data from JSON using CoffeeScript?
I want to grab a specific piece of data from a massive JSON string. The entire string would be more than 10 pages long if posted here, so I'm just including an example snippet:
{ name: '',
keys:
[ 'statType',
'count',
'dataVersion',
'value',
'championId',
'futureData' ],
object:
{ statType: 'TOTAL_SESSIONS_PLAYED',
count: { value: 5 },
dataVersion: 0,
value: { value: 5 },
championId: { value: 31 },
futureData: null },
encoding: 0 }
How can I use CoffeeScript to:
parse that string to locate the object with a specific value, such as TOTAL_SESSIONS_PLAYED,
take the numerical value from that object (the value field), and
ideally, append that value into an external text file?
I am pretty much a super noob programmer. Basically, how could I, in this example, take that 5 value from the object labelled TOTAL_SESSIONS_PLAYED, and append it into a text file using CoffeeScript?
Whether you're doing this in the browser or in Node, you should be able to pass the JSON string to JSON.parse and pick out the value you want. You can then append to a file using Node's fs module like this: https://stackoverflow.com/a/11267583/659910.
fs = require 'fs'
# Sample JSON string.
json = '{ "statType": "TOTAL_SESSIONS_PLAYED", "count": { "value": 5 }, "dataVersion": 0 }'
data = JSON.parse(json)
fs.appendFile('/tmp/data.txt', data.count.value, (error) -> throw error if error)