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
Related
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.
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 1 year ago.
Improve this question
I know there are a lots of people that has run into the same issue but still here I am. I'm pretty sure my code is correct and still the resulting struct is empty.
Function :
func PostAdminHandler(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-type", "application/json")
var admin admin.Admin
json.NewDecoder(r.Body).Decode(&admin)
fmt.Println(admin)
_, err := PostAdmin(admin)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
Console print :
{ ObjectID("000000000000000000000000")}
Structure :
package entity
import "go.mongodb.org/mongo-driver/bson/primitive"
type Admin struct {
FirstName string
LastName string
Email string
Password string
Role string
Campus primitive.ObjectID
}
Route :
adminRoute.HandleFunc("/admin", admin.PostAdminHandler).Methods("POST")
Json data I'm sending through Insomnia :
{
"FirstName": "Jeanne",
"LastName": "Darc",
"Email": "jeanne.darc#rouen.fr",
"Password": "JeanneDarc2022",
"Role": "admin",
"Campus": "60d5a25ff4d722d3b77d1929",
}
Error i'm getting from decoder :
invalid character '}' looking for beginning of object key string
This RFC:
https://datatracker.ietf.org/doc/html/rfc7159
specifies the JSON object format as:
An object structure is represented as a pair of curly brackets
surrounding zero or more name/value pairs (or members). A name is a
string. A single colon comes after each name, separating the name
from the value. A single comma separates a value from a following
name. The names within an object SHOULD be unique.
object = begin-object [ member *( value-separator member ) ]
end-object
member = string name-separator value
So, no trailing commas.
Remove the last comma in the input.
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 don't understand why this doesn't work for this type of structure.
package main
import (
"fmt"
)
var myStruct struct {
number float64
word string
toggle bool
}
myStruct.number = 3.14
myStruct.word = "pie"
myStruct.toggle = true
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
If I try to change myStruct.number outside main, I get a compilation error syntax error: non-declaration statement outside function body, but it works fine inside the function. With variables or other types of data structures, it works fine to change values outside main scope, but not with struct.
The program is an example from Head first Go, and even if I searched at least three more books and google for more information, I haven't found something similar that would be better explained.
https://play.golang.org/p/brocZzWuRae
package main
import (
"fmt"
)
var myStruct = struct {
number float64
word string
toggle bool
}{
number: 3.14,
word: "pie",
toggle: true,
}
func main() {
//myStruct.number = 3.14
//myStruct.word = "pie"
//myStruct.toggle = true
fmt.Println(myStruct.number)
fmt.Println(myStruct.toggle)
fmt.Println(myStruct.word)
}
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 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 4 years ago.
Improve this question
I work with Go.
I would like to parse a JSON file. But I only need just one array from the JSON file, not all the structure.
This is the JSON file : link
I only need the array of items.
How can I extract just this array from the JSON?
That depends of the definition of your structs. if you want only the array of items, you should unmarshal the main structure and then get the items array.
something like this
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
)
type Structure struct {
Items []Item `json:"items"`
}
type Item struct {
ID int `json:"id"`
Name string `json:"name"`
}
func main() {
data, err := ioutil.ReadFile("myjson.json")
if err != nil {
fmt.Println(err)
os.Exit(1)
}
structure := new(Structure)
json.Unmarshal(data, structure)
theArray := structure.Items
fmt.Println(theArray)
}
The Unmarshal will ignore the fields you don't have defined in your struct. so that means you should add only what you whant to unmarshal
I used this JSON
{
"total_count": 123123,
"items": [
{
"id": 1,
"name": "name1"
},
{
"id": 2,
"name": "name2"
}
]
}