登录
首页 >  Golang >  Go问答

JSON-LD 解析错误:禁止获取远程上下文

来源:stackoverflow

时间:2024-02-22 23:09:24 442浏览 收藏

从现在开始,我们要努力学习啦!今天我给大家带来《JSON-LD 解析错误:禁止获取远程上下文》,感兴趣的朋友请继续看下去吧!下文中的内容我们主要会涉及到等等知识点,如果在阅读本文过程中有遇到不清楚的地方,欢迎留言呀!我们一起讨论,一起学习!

问题内容

我正在尝试使用包 https://godoc.org/github.com/emersion/go-jsonld 解组 json-ld

package main

import (

    "fmt"   
    jsonld "github.com/emersion/go-jsonld"
)
func main() {

    text := `{"@context": ["http://schema.org", { "image": { "@id": "schema:image", "@type": "@id"}  }],"id": "http://www.wikidata.org/entity/q76","type": "person","name": "barack obama","givenname": "barack","familyname": "obama","jobtitle": "44th president of the united states","image": "https://commons.wikimedia.org/wiki/file:president_barack_obama.jpg"}`
    textbytes := []byte(text)
    var container interface{}
    err := jsonld.unmarshal(textbytes,container)
    fmt.println("error while unmarshalling json-ld: ",err.error())
    fmt.println("output: ",container)
}

输出

Error while unmarshalling json-ld:  jsonld: fetching remote contexts is disabled
Output:  

我还检查了同一包中其他解组函数,例如 func unmarshalwithcontext(b []byte, v interface{}, ctx *context) error 但没有帮助。


解决方案


您的输入中有一个远程上下文,因此您需要按以下方式获取它:

package main

import (
    "bytes"
    "fmt"

    jsonld "github.com/emersion/go-jsonld"
)

type person struct {
    ID    string           `jsonld:"@id"`
    Name  string           `jsonld:"name"`
    URL   *jsonld.Resource `jsonld:"url"`
    Image *jsonld.Resource `jsonld:"image"`
}

func main() {

    text := `{"@context": ["http://schema.org", { "image": { "@id": "schema:image", "@type": "@id"}  }],"id": "http://www.wikidata.org/entity/Q76","type": "Person","name": "Barack Obama","givenName": "Barack","familyName": "Obama","jobTitle": "44th President of the United States","image": "https://commons.wikimedia.org/wiki/File:President_Barack_Obama.jpg"}`
    textBytes := []byte(text)
    var container person
    dec := jsonld.NewDecoder(bytes.NewReader(textBytes))
    dec.FetchContext = func(url string) (*jsonld.Context, error) {
        var fetchedContext jsonld.Context //TODO fetch the context
        return &fetchedContext, nil
    }

    err := dec.Decode(&container)
    fmt.Println("Error while unmarshalling json-ld: ", err)
    fmt.Println("Output: ", container)
}

或者在输入中提供架构。输入输出示例可以参考tests

到这里,我们也就讲完了《JSON-LD 解析错误:禁止获取远程上下文》的内容了。个人认为,基础知识的学习和巩固,是为了更好的将其运用到项目中,欢迎关注golang学习网公众号,带你了解更多关于的知识点!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>