如何解析在JavaScript中嵌套了转义JSON的JSON?

时间:2019-02-26 15:51:29

标签: javascript json

更新:此JSON只是示例之一,我需要读取这些JSON文件并将它们传递给接受JSONObject的函数。

我有一个这样的JSON-

const existingState = {
  rules: [{
    "id": "cbd6defd-5f60-447f-8d31-f9ce75a7604a",
    "matches": "android",
    "url": "http://www.google.co.uk",
    "what": "platform"
  }]
}

const rules = [
      {what: "platform", matches: "ios"},
      {what: "platform", matches: "android"},
      {what: "platform", matches: "windows"},
      {what: "platform", matches: "linux"},
      {what: "platform", matches: "mac"}
    ]

const mergedState = rules.reduce((merged, rule) => {
  if (!merged.some(({what, matches}) => rule.what === what && rule.matches === matches)) 
    merged.push(rule)
  return merged
}, existingState.rules.slice())

console.log(mergedState);

我正在尝试解析使用-

#!/usr/bin/env python

import argparse
import redis

p = argparse.ArgumentParser()
p.add_argument("-i", '--host', type=str, default="127.0.0.1", help="redis host", required=False)
p.add_argument("-p", '--port', type=int, default=6379, help="redis port", required=False)
p.add_argument("-n", '--db', type=int, default=0, help="redis database", required=False)

args = p.parse_args()

r = redis.Redis(host=args.host, port=args.port, db=args.db)

try:
    keys = r.keys()

    for key in keys:
        if r.ttl(key) < 0:
            print(key)
except KeyboardInterrupt:
    pass

这会在此部分引发错误- { "log": { "version": "1.2", "entries": [ { "response": { "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [ { "name": "Date", "value": "Tue, 19 Feb 2019 13:50:34 GMT" }, { "name": "CF-RAY", "value": "4ab934095ceacc4c-ZRH" }, { "name": "Content-Encoding", "value": "gzip" } ], "cookies": [], "content": { "size": 155, "mimeType": "application/json", "compression": 0, "text": "{\"ip\":\"45.64.195.115\",\"ip_decimal\":759219059,\"country\":\"India\",\"country_eu\":false,\"country_iso\":\"IN\",\"city\":\"nocity\",\"latitude\":98.975,\"longitude\":92.8258}" }, "redirectURL": "", "headersSize": 230, "bodySize": 155, "_transferSize": 385 }, "cache": {}, "timings": { "blocked": 6.805000007039867, "dns": -1, "ssl": -1, "connect": -1, "send": 0.22000000000000064, "wait": 174.87700000413787, "receive": 11.549999995622784, "_blocked_queueing": 0.8590000070398673 }, "serverIPAddress": "100.28.12.103", "_initiator": { "type": "other" }, "_priority": "VeryHigh", "connection": "509100", "pageref": "page_2" } ] } }

因为它是一个转义的嵌套JSON。

我该怎么做?我找到了一种方法here,但不适用于此问题。

3 个答案:

答案 0 :(得分:0)

您的json已经可以用作javascript对象

const myJSON = {
   "log":{
      "version":"1.2",
      "entries":[
         {
            "response":{
               "status":200,
               "statusText":"OK",
               "httpVersion":"HTTP/1.1",
               "headers":[
                  {
                     "name":"Date",
                     "value":"Tue, 19 Feb 2019 13:50:34 GMT"
                  },
                  {
                     "name":"CF-RAY",
                     "value":"4ab934095ceacc4c-ZRH"
                  },
                  {
                     "name":"Content-Encoding",
                     "value":"gzip"
                  }
               ],
               "cookies":[

               ],
               "content":{
                  "size":155,
                  "mimeType":"application/json",
                  "compression":0,
                  "text":"{\"ip\":\"45.64.195.115\",\"ip_decimal\":759219059,\"country\":\"India\",\"country_eu\":false,\"country_iso\":\"IN\",\"city\":\"nocity\",\"latitude\":98.975,\"longitude\":92.8258}"
               },
               "redirectURL":"",
               "headersSize":230,
               "bodySize":155,
               "_transferSize":385
            },
            "cache":{

            },
            "timings":{
               "blocked":6.805000007039867,
               "dns":-1,
               "ssl":-1,
               "connect":-1,
               "send":0.22000000000000064,
               "wait":174.87700000413787,
               "receive":11.549999995622784,
               "_blocked_queueing":0.8590000070398673
            },
            "serverIPAddress":"100.28.12.103",
            "_initiator":{
               "type":"other"
            },
            "_priority":"VeryHigh",
            "connection":"509100",
            "pageref":"page_2"
         }
      ]
   }
}

如果您想解析“ log.entries.response.content.text”,则可以执行以下操作

if (myJSON.log && myJSON.log.entries && myJSON.log.entries.length > 0) {
  for (const element of myJSON.log.entries) {
    if (element.response && element.response.content && element.response.content.text) {
      try {
        element.response.content.text = JSON.parse(element.response.content.text);
      } catch (error) {
        console.log('do nothing')
      }
    }
  }
}

答案 1 :(得分:0)

这是因为

myJson.log.entries[0].response.content.text

是在JSON字符串化之后,因此您需要先解析它,然后再解析整个对象。
这样做:

myJson.log.entries[0].response.content.text = JSON.parse(myJson.log.entries[0].response.content.text);

答案 2 :(得分:0)

非常简单:您只需要知道何时有javascript对象,以及何时有代表JSON格式的javascript对象的字符串。

在您给出的示例中,您的外部对象看起来像一个javascript对象,而不是JSON字符串。因此,您无需解析它,只需对其进行操作即可。嵌入其中的是一个名为“ text”的元素,它是JSON字符串。您可以访问text元素,然后可以使用JSON.parse进行解析。这是一个示例(在其中,我删除了顶级对象中的大多数无关内容):

const myObj = {"log": {
        "version": "1.2",
        "entries": [
            {
                "content": {
                    "size": 155,
                    "mimeType": "application/json",
                    "compression": 0,
                    "text": "{\"ip\":\"45.64.195.115\",\"ip_decimal\":759219059,\"country\":\"India\",\"country_eu\":false,\"country_iso\":\"IN\",\"city\":\"nocity\",\"latitude\":98.975,\"longitude\":92.8258}"
                }
            }
        ]
    }
};

const anotherObj = JSON.parse(myObj.log.entries[0].content.text);

console.log(JSON.stringify(anotherObj, null, 3));

这将产生以下输出:

{
   "ip": "45.64.195.115",
   "ip_decimal": 759219059,
   "country": "India",
   "country_eu": false,
   "country_iso": "IN",
   "city": "nocity",
   "latitude": 98.975,
   "longitude": 92.8258
}