Home Php C# Sql C C++ Javascript Python Java Go Android Git Linux Asp.net Django .net Node.js Ios Xcode Cocoa Iphone Mysql Tomcat Mongodb Bash Objective-c Scala Visual-studio Apache Elasticsearch Jar Eclipse Jquery Ruby-on-rails Ruby Rubygems Android-studio Spring Lua Sqlite Emacs Ubuntu Perl Docker Swift Amazon-web-services Svn Html Ajax Xml Java-ee Maven Intellij-idea Rvm Macos Unix Css Ipad Postgresql Css3 Json Windows-server Vue.js Typescript Oracle Hibernate Internet-explorer Github Tensorflow Laravel Symfony Redis Html5 Google-app-engine Nginx Firefox Sqlalchemy Lucene Erlang Flask Vim Solr Webview Facebook Zend-framework Virtualenv Nosql Ide Twitter Safari Flutter Bundle Phonegap Centos Sphinx Actionscript Tornado Register | Login | Edit Tags | New Questions | 繁体 | 简体


10 questions online user: 90

140
votes
answers
21 views
+10

How do I encode a JavaScript object as JSON?

Is there a good way to encode a JavaScript object as JSON?

I have a list of key value pairs...where the name is from a checkbox, and the value is either true or false based on whether the box is checked or not:

var values = {};
$('#checks :checkbox').each(function() { values[this.name]=this.checked; }); 

I want to pass these values into a JSON object so store into a cookie to render a table (Columns will be added according to what the user checks off).

Does anyone know a solution?

up vote 112 down vote accepted favorite
沙发
+1120
+50

我認為你可以使用 JSON.stringify

  //在每個循環之後JSON.stringify(values);  
     
			
        

我把它放在警報中()但沒有出現 - daniel langer 12年6月6日18:33

@daniellanger - 基於你的評論,這就是答案。你需要做一些調試,看看為什麼事情沒有出現 - Adam Rackis 12年6月6日18:37

那麼如何將其保存為文件/將其存儲為cookie? - daniel langer 12年6月6日18:39

IE 10正在給出:JavaScript運行時錯誤:'JSON'未定義 - Matthew Lock 2013年3月22日6:27

IE8及更高版本支持本機JSON方法。話雖如此,在IE中它們僅在標準模式下可用。 - 波阿斯2014年5月14日13:13

+280

所有主流瀏覽器現在都包含原生JSON編碼/解碼。

  //對對象進行編碼(這會生成一個字符串)var json_str = JSON.stringify(myobject); //解碼(這會產生一個對象)var obj = JSON.parse(json_str);   

請注意,只會編碼有效的JSON數據。例如:

  var obj = {'foo':1,'bar':( function(x){return x;})} JSON.stringify(obj)//  - &gt ; “{”foo“:1}”  

有效的JSON類型包括:對象,字符串,數字,數組, true false null

一些JSON資源:

我的哈希是有效的JSON數據嗎? - 丹尼爾·朗格12年6月6日19:10

好吧,它們在javascript中被稱為“對象”。但是,是的,布爾值可以用JSON表示。 - vezult 12年6月6日19:16

0
votes
answers
31 views
+10

反序列化自定義JsonConverter中的嵌套對象列表

0

我做了一個自定義JSON轉換器來處理我收到的JSON,但我有一些解析嵌套對象列表的麻煩。我的JSON目前看起來像這樣:反序列化自定義JsonConverter中的嵌套對象列表

JSON: 

{ 
"messageID": "1", 
"item": 
    { "type": "text", 
    "textlist": [ { "text": "just some text" }] 
    } 
} 

在我的情況下,我創建了幾個類可以轉換爲。我有一個消息類應用轉換器的項目。 item屬性是一個接口,它具有TextItem類形式的實現。

public class Message 
    { 
    [JsonProperty("messageID")] 
    public string messageID { get; set; } 

    [JsonConverter(typeof(ItemConverter))] 
    public IItem item { get; set; } 

    public Message(string msgID, IItem itm) 
    { 
     messageID = msgID; 
     item = itm; 
    } 
} 

public class TextItem : IItem 
{ 
    [JsonProperty("type")] 
    public string type { get; set; } 
    [JsonProperty("textlist")] 
    public List<Text> textlist { get; set; } 

    string IItem.Type 
    { 
     get => type; 
     set => type = value; 
    } 

    public TextItem(List<Text> txtlst) 
    { 
     type = "text"; 
     textlist = txtlst; 
    } 
} 

public class Text 
{ 
    [JsonProperty("text")] 
    public string text { get; set; } 

    public Text(string txt) 
    { 
     text = txt; 
    } 
} 

有相當多的不同類型的項目,這就是爲什麼我有ItemConverter:

public class ItemConverter : JsonConverter 
    { 
     public override object ReadJson(JsonReader reader, 
     Type objectType, object existingValue, 
     JsonSerializer serializer) 
    { 
     var jsonObject = JObject.Load(reader); 
     var item= default(IItem); 
     switch (jsonObject["type"].Value<string>()) 
     { 
      case "text": 
       item= new TextItem(jsonObject["textlist"].Value<List<Text>>()); 
       break; 
    // omitted non relevant cases 
     } 

     serializer.Populate(jsonObject.CreateReader(), item); 
     return item; 
    } 
} 

然而,調用DeserializeObject只會導致錯誤

JsonConvert.DeserializeObject<Message>(userMessage) 

// I get the following error: 
System.ArgumentNullException: Value cannot be null. 

所有我的其他案例(沒有列表)處理得很好。關於爲什麼嵌套列表未正確轉換的任何想法?

沙发
0
0

你的類都搞砸了,

使用public string type { get; set; }讓你的項目,你需要

你的類可能是這個樣子

public class Textlist 
{ 
    public string text { get; set; } 
} 

public class Item 
{ 
    public string type { get; set; } 
    public List<Textlist> textlist { get; set; } 
} 

public class RootObject 
{ 
    public string messageID { get; set; } 
    public Item item { get; set; } 
} 

,現在你可以在RootObject

反序列化
+0

我按照你所描述的修復了我的課程(也在原始文章中更新了它)。它仍然產生相同的結果。 – Tippi

+0

犯了小錯,這是正確的答案 – Tippi

0
votes
answers
23 views
+10

JSON_SET在MariaDB的,不插入數據

0

在MariaDB的文檔,它說,JSON_SET插入或更新信息,而只是JSON_INSERT插入和JSON_REPLACE唯一替代品。JSON_SET在MariaDB的,不插入數據

我使用下面的代碼,我需要插入的信息,如果它不存在,或者更新的,如果它已經存在。

的問題是,它僅更新,當它已經存在,並且它不會插入,如果它不存在。

MariaDB docs

UPDATE myTable SET config = JSON_SET(config, '$.person.name', 'zeca', '$.person.details.age', '87') WHERE id = 127 

如果 「詳細信息」,在爲myTable的 「配置」 領域已經存在, 「時代」 將被註冊。如果「詳細信息」仍然是不存在的,我要註冊details.age,但它沒有註冊。

+0

你得到它的工作? – musashii

沙发
0
0

我不能測試我的代碼,但也許你能得到它的東西像這樣工作

UPDATE myTable SET config = JSON_MERGE(config, '{"person": {}'), config = JSON_SET(config, '$.person.name', 'zeca', '$.person.details.age', '87') WHERE id = 127

板凳
0
0

調整了一句,因爲你需要:

UPDATE `myTable` 
    SET `config` = JSON_SET(`config`, '$.person.name', 'zeca'), 
     `config` = IF(JSON_EXISTS(`config`, '$.person.details') IS NOT NULL, 
     JSON_SET(
      `config`, 
      '$.person.details', 
      JSON_OBJECT('age', 87) 
     ), 
     JSON_INSERT(
      `config`, 
      '$.person', 
      JSON_OBJECT('details', 
      JSON_OBJECT('age', 87) 
     ) 
     ) 
    ) 
WHERE `id` = 127; 

dbfiddle

0
votes
answers
17 views
+10

Elasticsearch Java API查詢JSON解析器

1

所以我有一個elasticsearch數據庫,我用它來存儲聯繫人。我做下面的查詢。Elasticsearch Java API查詢JSON解析器

public String getAllContacts() throws IOException { 

    SearchResponse response = client.prepareSearch("contact").get(); 

    return response.toString(); 
} 

於是我得到這樣 Json result from query

一個結果,那麼我想提出的JSON數據到我的聯繫對象類

import com.fasterxml.jackson.annotation.JsonIgnoreProperties; 
import javax.xml.bind.annotation.XmlRootElement; 
import java.util.Date; 
@JsonIgnoreProperties(ignoreUnknown = true) 
@XmlRootElement 
public class Contact { 

    private long id; 
    private String name; 
    private Date date; 

    public Contact() {} 
    public Contact(long id, String name, Date date) { 
     this.id = id; 
     this.name = name; 
     this.date = date; 
    } 
    public long getId() {return id;} 
    public void setId(long id) {this.id = id;} 
    public String getName() { return name;} 
    public void setName(String name) {this.name = name;} 
    public Date getDate() { return date; } 
    public void setDate(Date date) { this.date = date; } 
} 

後來我但是,當我嘗試映射JSON反對使用下面的代碼我得到的錯誤

ObjectMapper mapper = new ObjectMapper(); 
    List<Contact> myObjects = mapper 
.readValue(response.toString(), mapper 
.getTypeFactory() 
.constructCollectionType(List.class, Contact.class)); 

其中之一許多錯誤

Can not deserialize instance of java.util.ArrayList out of START_OBJECT token 

,所以我認爲這個問題是所有這些來自查詢,如果我得到一個乾淨的JSON這樣{"id":"2","name";"dinu"}它的工作原理其他的東西(我沒有手動測試),但它與許多其他的東西,例如作爲JSON文件(標題元數據)的頂部(檢查上面的JSON結果圖像)。

所以我覺得我有2個選擇: -

選項1: - 得到elasticsearch DB乾淨的結果,所以我需要修改的搜索查詢。我不知道彈性搜索是否可以實現。如果是的話,有人可以提出如何修改查詢的建議(在Java API中)。

選項2: - 篩選出JSON文件並刪除所有不需要的東西,然後將其變爲Contact對象。我試圖GSON和傑克遜都與未經過濾的文件失敗。如果有任何先進或自定義的方式來過濾讓我知道。

選項3: - 我完全錯了,有一個更好的簡單的方法來做它。請讓我知道。

UPDATE 看這個: - https://www.youtube.com/watch?v=YgKcVBbvy2U

,所以我試圖用GSON將序列

則異常不來,但系列化的「意外‘d’」後,我得到響應上述方式也在原始的甲酸鹽中,它每次輸出這個[email protected]我發送一個GET響應@符號更改後的文本。

沙发
0
3

設定值到相應的對象的方法您需要對搜索匹配和反序列化值執行迭代。

SearchResponse response = client.prepareSearch("contact").get(); 
ObjectMapper mapper = new ObjectMapper(); 
List<Contact> lst = new ArrayList<Contact>(); 
for(SearchHit hit : response.getHits().getHits()) { 
    Contact c = mapper.readValue(hit.getSourceAsString(), Contact.class); 
    lst.add(c); 
} 

如果您需要再次s erialize它作爲一個JSON列表,你可以簡單地得到作爲JSON

String lstString = mapper.writeValueAsString(lst); 

上面提到的ObjectMapper距離Jackson數據綁定庫。這是非常好的,比Gson

import com.fasterxml.jackson.databind.ObjectMapper; 
板凳
0
0

從響應JSON中,hits:標籤應該是包含屬性index,type,id,score,source..etc的列表。請嘗試檢索包含具有聯繫人的對象的匹配列表對象

+0

我想要做的是刪除命中列表對象,只獲取JSON格式的聯繫人數據。 – Dinushka

地板
0
0

不確定這是否有助於獲得您要查找的內容。我只是將你的字符串添加到文本文件中

Object obj = new JSONParser()。parse(new FileReader(「data。TXT 「));

// typecasting obj to JSONObject 
    JSONObject jo = (JSONObject) obj; 

    // getting hits 
    Map hits = ((Map)jo.get("hits")); 
    JSONArray array = null; 
    // iterating hits Map 
    Iterator<Map.Entry> itr1 = hits.entrySet().iterator(); 
    while (itr1.hasNext()) { 
     Map.Entry pair = itr1.next(); 
     System.out.println(pair.getKey() + " : " + pair.getValue()); 
     if(pair.getKey().equals("hits")){ 
      array = (JSONArray) pair.getValue(); 

     } 
    } 

    System.out.println(array); 

[{」 _index 「:」 接觸 「 」_類型「: 」ID「, 」_ ID「:2 」_分數「:1},{ 」_索引「:」 接觸」, 「_類型」: 「ID」, 「_ ID」:4, 「_分數」:1}]

你或許可以寫可以通過迭代JSON陣列

40
votes
answers
20 views
+10

Which browsers allow cross domain ajax calls with Access-Control-Allow-Origin: *?

Which browsers allow cross domain ajax calls with Access-Control-Allow-Origin: *? I am setting a REST service and trying to decide if I need to support JSONP to allow cross domain javascript access or if it is good enough to set the Access-Control-Allow-Origin header.

up vote 40 down vote accepted favorite
沙发
+400
+50

這是一個參考資料,表明現代瀏覽器中的支持是合理的(但請參閱最後的說明)這個答案),假設客戶端代碼故意處理IE問題。(IE8和IE9支持CORS,但不能通過 XMLHttpRequest - 你必須使用 XDomainRequest ,而且值得注意的是 jQuery Prototype 在他們的ajax包裝中為你做這件事 - 我不喜歡了解其他圖書館< / A>。IE10 終於使它正確。)該頁面實質上說明了桌面版本支持CORS

  • IE8 +(通過 XDomainRequest ),IE10 +(正確)
  • Firefox 3.6+
  • Safari 4.0 +
  • Chrome 6 +
  • Opera 12.1 +

    ...以及

    • iOS Safari 3.2 +
    • Android瀏覽器2.1 +

      您必須問自己目標市場是什麼以及他們是否可能仍在使用舊版本的IE,因為rel =“noreferrer”>這非常重要你的目標人群。但總的來說,你仍然(目前)可能想看一下JSONP界面 - 即使在美國大多數家庭市場,IE6 + IE7 =約20%的用戶。我不知道很多網站可以忽略五分之一的市場。:-)如果你看一下企業用戶,或亞洲,非洲或中美洲的用戶,這個數字會明顯上升。 2010年的情況就是如此。在2013年,中國真的是唯一堅持使用IE6的人(那裡有> 24%)。在全球範圍內,IE6和IE7用戶已經轉向IE8和IE9,甚至大公司和政府用戶也最終“了解”了安全風險。IE8將與我們在一段時間(因為IE在Windows XP上有很高的優勢),

可惜我不能投票兩次(一次用於支持表,一次用於警告,以盡量減少IE 6(/ 7)用戶的數量)。 - Marcel Korpel 2010年12月9日23:01

我為你做了第二次,問題解決了^^ - EgeÖzcan2010年12月9日在23:04

好消息是,與最後一段有關的數字現在正在迅速下降。IE6在美國市場現在低於1%; 我沒有IE7的數字,因為NetApplications現在正在為他們的地理過濾器收費(可以理解!)。但IE7在全球的市場份額僅佔IE6市場份額的三分之二左右,因此對於美國本土市場,我們可能就在那裡。奇怪的是,Opera 11仍然不支持CORS,但據稱將會支持12個。 - TJ Crowder 12年3月23日12:40

0

使用Access-Control-Allow-Origin:*時遇到了一些問題。我認為它與cookie和預檢請求(POST)有關。因此,最好指定您將從哪個域進行這些調用。

這是對的。如果設置為*通配符,許多瀏覽器將忽略Access-Control-Allow-Origin。 - Rebs 2015年12月3日1:30

0
votes
answers
13 views
+10

Ansible - 結合兩個變量將[u ...]添加到其中之一

1

我想將兩個字符串組合在一起。一個從set_facts中提取,另一個在playbook中定義爲變量。但是,當我運行調試。我得到額外的字符,如[u''] 但沒有得到乾淨的輸出。Ansible - 結合兩個變量將[u ...]添加到其中之一

這是我想要的結果:

final_list: usera,userb,userc,userd,usere,userf 

但是,這是我得到的結果是:

ok: [localhost] => { 
    "final_list": "[u'usera,userb,userc'],userd,usere,userf" 
} 

這裏是我的劇本:

- vars: 
     list_2: "userd,usere,userf" 
    - set_fact: 
     list_1="{{ parent_hgdata.json|json_query("parameters[?name=='usernames'].value") }}" 

- name: verify list 1 output 
     debug: 
     var: list_1 

### The above task gives me the right output for list_1 

    - name: Combining list _1 and list_2 
     set_fact: 
     final_list: "{{ list_1 }},{{ list_2 }}" 

    - name: Now verify the final_list 
     debug: 
     var: final_list 

現在,當我調試final_list。它紅粉我不潔淨的輸出

"final_list": "[u'usera,userb,userc'],userd,usere,userf" 
沙发
0
1

list_1是一個列表對象,list_2是一個字符串。

如果你想在年底的字符串,則需要先使用join filter列表轉換爲字符串,然後連接具有其餘部分:

set_fact: 
    final_list: "{{ list_1 | join(‘,’) }},{{ list_2 }}" 
+0

真棒。有效。好極了!。 techraf,你真了不起。感謝您的解釋以及:) – sherri

209
votes
answers
17 views
+10

what is the difference between json and xml [closed]

What is the difference between JSON and XML?

沙发
+1530

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

重複並解釋XML實際上是一種標記語言而不是數據格式非常有用。謝謝你寫這個! - jrahhali於2017年4月1日15:23

板凳
+270

They are both data formats for hierarchical data, so while the syntax is quite different, the structure is similar. Example:

JSON:

{
  "persons": [
    {
      "name": "Ford Prefect",
      "gender": "male"
    },
    {
      "name": "Arthur Dent",
      "gender": "male"
    },
    {
      "name": "Tricia McMillan",
      "gender": "female"
    }
  ]
}

XML:

<persons>
  <person>
    <name>Ford Prefect</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Arthur Dent</name>
    <gender>male</gender>
  </person>
  <person>
    <name>Tricia McMillan</name>
    <gender>female</gender>
  </person>
</persons>

The XML format is more advanced than shown by the example, though. You can for example add attributes to each element, and you can use namespaces to partition elements. There are also standards for defining the format of an XML file, the XPATH language to query XML data, and XSLT for transforming XML into presentation data.

The XML format has been around for some time, so there is a lot of software developed for it. The JSON format is quite new, so there is a lot less support for it.

While XML was developed as an independent data format, JSON was developed specifically for use with Javascript and AJAX, so the format is exactly the same as a Javascript literal object (that is, it's a subset of the Javascript code, as it for example can't contain expressions to determine values).

“格式與Javascript文字對象完全相同。” - 不完全是,JSON文本是JS對象文字的子集。 - Daniel Earwicker 2010年4月12日7:55

@Daniel:當然它是一個子集,你當然不能在Javascript中編寫任何東西,例如調用函數來獲取成員的值。這就是為什麼你貶低了答案? - Guffa 2010年4月12日9:20

唉......我其實打算投票給你,現在除非你進行編輯,否則不會讓我修復它。檢查“與a完全相同”到“a的格式的子集”,我會盡快修復它。 - Daniel Earwicker 2010年4月12日9:48

言語讓我失望...... - Martin Bean 2010年4月12日9:55

完成。(面掌) - Daniel Earwicker 2010年4月12日10:00

地板
+200

The difference between XML and JSON is that XML is a meta-language/markup language and JSON is a lightweight data-interchange. That is, XML syntax is designed specifically to have no inherent semantics. Particular element names don't mean anything until a particular processing application processes them in a particular way. By contrast, JSON syntax has specific semantics built in stuff between {} is an object, stuff between [] is an array, etc.

A JSON parser, therefore, knows exactly what every JSON document means. An XML parser only knows how to separate markup from data. To deal with the meaning of an XML document, you have to write additional code.

To illustrate the point, let me borrow Guffa's example:

{   "persons": [
  {
    "name": "Ford Prefect",
    "gender": "male"
 },
 {
   "name": "Arthur Dent",
   "gender": "male"
  },
  {
    "name": "Tricia McMillan",
    "gender": "female"
  }   ] }

The XML equivalent he gives is not really the same thing since while the JSON example is semantically complete, the XML would require to be interpreted in a particular way to have the same effect. In effect, the JSON is an example uses an established markup language of which the semantics are already known, whereas the XML example creates a brand new markup language without any predefined semantics.

A better XML equivalent would be to define a (fictitious) XJSON language with the same semantics as JSON, but using XML syntax. It might look something like this:

<xjson>   
  <object>
    <name>persons</name>
    <value>
      <array>
         <object>
            <value>Ford Prefect</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Arthur Dent</value>
            <gender>male</gender>
         </object>
         <object>
            <value>Tricia McMillan</value>
            <gender>female</gender>
         </object>
      </array>
    </value>   
  </object> 
 </xjson>

Once you wrote an XJSON processor, it could do exactly what JSON processor does, for all the types of data that JSON can represent, and you could translate data losslessly between JSON and XJSON.

So, to complain that XML does not have the same semantics as JSON is to miss the point. XML syntax is semantics-free by design. The point is to provide an underlying syntax that can be used to create markup languages with any semantics you want. This makes XML great for making up ad-hoc data and document formats, because you don't have to build parsers for them, you just have to write a processor for them.

But the downside of XML is that the syntax is verbose. For any given markup language you want to create, you can come up with a much more succinct syntax that expresses the particular semantics of your particular language. Thus JSON syntax is much more compact than my hypothetical XJSON above.

If follows that for really widely used data formats, the extra time required to create a unique syntax and write a parser for that syntax is offset by the greater succinctness and more intuitive syntax of the custom markup language. It also follows that it often makes more sense to use JSON, with its established semantics, than to make up lots of XML markup languages for which you then need to implement semantics.

It also follows that it makes sense to prototype certain types of languages and protocols in XML, but, once the language or protocol comes into common use, to think about creating a more compact and expressive custom syntax.

It is interesting, as a side note, that SGML recognized this and provided a mechanism for specifying reduced markup for an SGML document. Thus you could actually write an SGML DTD for JSON syntax that would allow a JSON document to be read by an SGML parser. XML removed this capability, which means that, today, if you want a more compact syntax for a specific markup language, you have to leave XML behind, as JSON does.

XML可以處理XJSON中對象節點下的名稱/值對序列的歧義嗎?我認為需要通過添加另一個級別(“屬性”或“屬性”或其他一些級別)或者通過在每個名稱和值之間添加共享屬性來指示哪個名稱與哪個值相關聯? - user2467065 18年4月4日13:42

其他答案稱XML為標記語言,JSON為表示格式。現在你說JSON是標記語言,XML實際上是一種“元”語言,無論這意味著什麼。你能澄清一下嗎?如果有人在面試中問我,我該怎麼回答? - Harsh Kanchina 18年6月26日13:15

4楼
+40

They're two different ways of representing data, but they're pretty dissimilar. The wikipedia pages for JSON and XML give some examples of each, and there's a comparison paragraph

5楼
+30

They are two formats of representation of information. While JSON was designed to be more compact, XML was design to be more readable.

是的,顯然有兩種不同的表現形式。但我不認為XML被認為更容易理解。JSON通常更緊湊,但我不認為這是一個重要的設計標準; 相反,可讀性,簡單性和易用性(尤其來自javascript)。更重要的是,兩個實際上具有完全不同的邏輯結構:XML是帶有分層模型的內聯標記格式; 和JSON是對象/框架/圖形模型的對象表示法(儘管“圖形”可能過分誇大,因為它沒有對象標識的概念)。 - StaxMan 2010年4月12日6:54

也許這是一個遲到的代表,但我想知道為什麼上面的答案被拒絕投票。(我應該說意見而不是回答)。@StaxMan所說的也是個人意見(甚至可以用“我不認為這是一個重要的設計標準”這樣的詞來證明。) - Stunner 2013年10月23日12:26

最初的答案沒有聲明任何支持“JSON設計為更緊湊,XML更易讀”的說法,如果我要DV它(我還沒有); 它沒有提到更多的根本區別。 - StaxMan 2013年10月23日15:39

6楼
+20

XML uses a tag structures for presenting items, like <tag>item</tag>, so an XML document is a set of tags nested into each other. And JSON syntax looks like a construction from Javascript language, with all stuff like lists and dictionaries:

{
 'attrib' : 'value',
 'array' : [1, 2, 3]
}

So if you use JSON it's really simple to use a JSON strings in many script languages, especially Javascript and Python.

在高級別是,但您的示例無效JSON:必須使用雙引號引用字段名稱。字符串值相同。 - StaxMan 2010年4月12日6:51

哎呀,對不起,現在已經修好了:) - Enchantner 2010年4月13日17:21

0
votes
answers
11 views
+10

解析來自json.loads()的數據,在python中

0

我試圖分析來自網站的數據。我解析了HTML以使用json.loads()獲取json數據。解析來自json.loads()的數據,在python中

??3210

所以現在我留下了數據,如下所示:

data = """ 
{'aggregateRating': {'reviewCount': 1691, 
        '@type'  : 'AggregateRating', 
        'ratingValue': 4.0}, 
'review': [{'reviewRating' : {'ratingValue': 5}, 
       'datePublished': '2017-10-31', 
       'description' : "I had a chance to see the Lakers ...", 
       'author'  : 'Andre W.'}] 
} 
"""" 

我感興趣的是「檢討」數組中返回從reviewRating的「ratingValue」整數。當我運行此腳本:

pd.DataFrame(data['review'], columns = ['reviewRating']) 

我得到這個:

reviewRating 
0 {'ratingValue': 5} 

相反,我在尋找的形式來獲取數據:

ratingValue 
0 5 

我已經嘗試各種變體如

pd.DataFrame(data['review'], columns = ['reviewRating']['ratingValue']) 
pd.DataFrame(data['review'], columns = ['reviewRating'][['ratingValue']]) 
pd.DataFrame(data['review']['reviewRating'], columns = ['ratingValue']) 

但我是s我不明白數據或大熊貓的下層結構。

因此,我最好清理{'ratingValue':5}作爲字符串以保留感興趣的整數,還是有一種簡單的方法來創建具有整數值'ratingValue的DataFrame 「?

謝謝。

+0

你使它看起來像如果'數據'是'json'字符串,而它可能是一個字典。 –

沙发
0
0

如果您使用 pandas.io.json您可以直接從json創建數據框。

使用您的樣本數據,我能夠輸出:

>>> frame = json_normalize(data) 

    author datePublished       description  
0 Andre W. 2017-10-31 I had a chance to see the Lakers ... 

    reviewRating.ratingValue 
0       5 

然後你就可以使用訪問評定值:

frame.at[0, 'reviewRating.ratingValue'] # which should give you 5

0
votes
answers
18 views
+10

如何在將導線添加到SuiteCRM時防止出現重複?

1

software fork之前的old SugarCRM one相比,developer guide for SuiteCRM有點不完整(至少在2017年第4季度)。因此,通過下載WordPress Plugin for SugarCRM,我能夠找出REST API和JSON,並通過以下代碼將銷售線索添加到SuiteCRM中。如何在將導線添加到SuiteCRM時防止出現重複?

現在我該如何防止家中電話,移動電話或電子郵件地址的重複?

<?php 

error_reporting(E_ALL); 
ini_set('display_errors','On'); 

header('Content-Type: text/plain'); 

CRM::loginCRM('admin','xxxxPASSWORDxxxxxx'); 

$aResult = CRM::addLead(array(
    'name' => 'John Doe', 
    'description' => 'sample description', 
    'salutation' => 'Mr.', 
    'first_name' => 'John', 
    'last_name' => 'Doe', 
    'do_not_call' => 'No', 
    'phone_home' => '202-111-2222', 
    'phone_mobile' => '202-111-2222', 
    'email1' => '[email protected]', 
    'primary_address_street' => '123 Main Street', 
    'primary_address_street2' => '', 
    'primary_address_street3' => '', 
    'primary_address_city' => 'New York', 
    'primary_address_state' => 'NY' 
)); 

print_r($aResult); 
CRM::logoutCRM(); 


die('OK'); 
///////////////////////// 

class CRM { 

private static $SessionID = ''; 

private static $URL = 'https://mycrmserver-example.com/service/v4_1/rest.php'; 

private static $User = ''; 
private static $Shadow = ''; 

public static function sendJSON($a) { 
    $s = file_get_contents(
    self::$URL, 
    false, 
    stream_context_create(
     array(
     'http' => array (
      'method' => 'POST', 
      'header' => 'Content-Type: application/x-www-form-urlencoded', 
      'content' => http_build_query($a) 
     ) 
    ) 
    ) 
); 
    $a2 = json_decode($s); 
    return $a2; 
} 

public static function loginCRM($sUser,$sPass) { 
    $sShadow = md5($sPass); 
    self::$User = $sUser; 
    self::$Shadow = $sShadow; 
    $asLogin = array (
    'method' => 'login', 
    'input_type' => 'JSON', 
    'response_type' => 'JSON', 
    'rest_data' => json_encode(array(
     'user_auth' => array(
     'user_name' => $sUser, 
     'password' => $sShadow, 
     'version' => 1 
    ), 
     'application_name' => 'RestTest', 
     'name_value_list' => array() 
    )) 
); 
    $a = self::sendJSON($asLogin); 
    self::$SessionID = $a->id; 
} 

public static function logoutCRM() { 
    $asLogin = array (
    'method' => 'logout', 
    'input_type' => 'JSON', 
    'response_type' => 'JSON', 
    'rest_data' => json_encode(array(
     'user_auth' => array(
     'user_name' => self::$User, 
     'password' => self::$Shadow, 
     'version' => 1 
    ), 
     'application_name' => 'RestTest', 
     'name_value_list' => array() 
    )) 
); 
    self::sendJSON($asLogin); 
} 

public static function addLead($a) { 
    $asNameValueList = array(); 
    foreach($a as $sKey => $sVal) { 
    $asNameValueList[] = array('name'=>$sKey,'value'=>$sVal); 
    } 
    $asAddEntry = array (
    'method' => 'set_entry', 
    'input_type' => 'JSON', 
    'response_type' => 'JSON', 
    'rest_data' => json_encode(array(
     'session' => self::$SessionID, 
     'module_name' => 'Leads', 
     'name_value_list' => $asNameValueList 
    )) 
); 
    $a = self::sendJSON($asAddEntry); 
    return $a; 
} 

} // end CRM 
沙发
0
2

將這些函數添加到您的CRM類中並在添加潛在客戶之前檢查它們。我從this answer得到了一些幫助,順便給了我一些見解。此外,我建議您採取措施來降低安全性,例如添加.htaccess或NGINX規則,該規則僅允許某些IP地址或需要某些標頭才能通過HTTP或/和/ service/*子文件夾到達/ service文件夾中的任何內容HTTPS。

public static function leadExistsByPhone($sHomePhone,$sMobilePhone) { 
    $sHomePhone = (empty($sHomePhone)) ? 'xxxxxinvalid' : $sHomePhone; 
    $sMobilePhone = (empty($sMobilePhone)) ? 'xxxxxinvalid' : $sMobilePhone; 
    $asCheck = array (
    'method' => 'get_entry_list', 
    'input_type' => 'JSON', 
    'response_type' => 'JSON', 
    'rest_data' => json_encode(array(
     'session' => self::$SessionID, 
     'module_name' => 'Leads', 
     'query' => " 
     leads.phone_home = '$sHomePhone' 
     OR leads.phone_mobile = '$sMobilePhone' 
     ", 
     'order_by' => 'leads.date_entered DESC', 
     'offset' => '0', 
     'select_fields' => array(), 
     'link_name_to_fields_array' => array(), 
     'max_results' => 999999, 
     'deleted' => false 
    )) 
); 
    $a = self::sendJSON($asCheck); 
    $nCount = @ $a->result_count; 
    $nCount = intval($nCount); 
    return ($nCount > 0); 
} 

public static function leadExistsByEmail($sEmail) { 
    if (!filter_var($sEmail, FILTER_VALIDATE_EMAIL)) { 
    die('DENIED: invalid email address format'); 
    } 
    $asCheck = array (
    'method' => 'get_entry_list', 
    'input_type' => 'JSON', 
    'response_type' => 'JSON', 
    'rest_data' => json_encode(array(
     'session' => self::$SessionID, 
     'module_name' => 'Leads', 
     'query' => " 
     leads.id IN 
     (
      SELECT email_addr_bean_rel.bean_id 
      FROM email_addr_bean_rel 
      JOIN email_addresses 
      ON  email_addr_bean_rel.email_address_id = email_addresses.id 
      WHERE 
      email_addresses.email_address = '$sEmail' 
     ) 
     ", 
     'order_by' => 'leads.date_entered DESC', 
     'offset' => '0', 
     'select_fields' => array(), 
     'link_name_to_fields_array' => array(), 
     'max_results' => 999999, 
     'deleted' => false 
    )) 
); 
    $a = self::sendJSON($asCheck); 
    $nCount = @ $a->result_count; 
    $nCount = intval($nCount); 
    return ($nCount > 0); 
} 
+0

如果您想更新現有的鉛,只需修改'leadExists *()'函數一點,讓你得到的ID,然後通過'id'的'$ asNameValueList'陣列中'set_entry'方法。 – Volomike

65
votes
answers
16 views
+10

downloading jackson.codehaus.org jar

I need to download a json parser so I go to the jackson.codehaus.org website. Instead of a convenient link to click and download the jar/jars, they have me going in circles. Does anyone know where the jars are -- exactly?

up vote 17 down vote accepted favorite
沙发
+170
+50

如果您點擊屏幕右邊的“下載”,請向下滾動到“下載,2.x”並點擊“核心”,即可直接下載。

+450

您可以改為使用此鏈接:

下載v2.9.7

更多常規鏈接

或轉到'jackson-core'。

更一般的鏈接:repo1.maven.org/maven2/com/fasterxml/jackson/core/jackson-core - rocknow 2014年7月2日在7:51

感謝上帝..最後我能夠下載.. + 1 - vins 2015年2月6日17:48

你在哪裡找到它?找不到下載鏈接(Master.zip不包含JAR)!只有直接鏈接工作! - 本2015年4月1日14:17

mvnrepository.com/search?q=jackson-core - Sujith PS 2015年4月2日10:04

不僅僅是偉大的! - JürgenK。2015年12月15日14:00

+10

這裡你可以找到傑克遜圖書館(版本2.4.0)。我從一個教程中得到了這些項目,你可以看到如何實現jackson,代碼和庫也可以下載: http://www.ibm.com/developerworks/java/library/j-hangman-app/index.html

+10

下一個替代鏈接: http://www.java2s.com/Code/ Jar / j / Downloadjacksonall199jar.htm

你可以在這裡找到包含完整文件列表的“AllIn”罐子。但最新版本是1.9.9。所以...

+10

請嘗試 / repositories / snapshots / com / fasterxml /傑克遜/核心

轉到相關目錄

  • jackson-annotations /
  • jackson-core /
  • jackson -databind /

    然後打開maven-metadata.xml文件。你可以在那裡找到最新版本的目錄。請注意,所有罐子都以發布日期重命名。

0

我知道這個問題已經有4年了,但傑克遜圖書館仍然很難找到,儘管Sujith PS的回答導致核心罐子,但這對我來說還不夠。

對於那些正在尋找核心 Databind 註釋的jar文件的人,我在這裡找到了它們:

< strong> http://mvnrepository.com/artifact/com.fasterxml.jackson.core

特別針對2.7.4版:

jackson-core-2.7.4.jar

jackson-databind-2.7.4.jar

jackson-annotations-2.7.4.jar 4 / jackson-annotations-2.7.4.jar“rel =”nofollow“> jackson-annotations-2.7.4.jar 4 / jackson-annotations-2.7.4.jar“rel =”nofollow“> jackson-annotations-2.7.4.jar