source

Python에서 두 개의 json 문자열을 병합하는 방법은 무엇입니까?

bestscript 2023. 3. 11. 09:03

Python에서 두 개의 json 문자열을 병합하는 방법은 무엇입니까?

최근에 Python을 사용하기 시작했고 JSON String 중 하나를 기존 JSON String과 연결하려고 합니다.저도 Zookeeper와 함께 작업하고 있기 때문에 Python kazoo 라이브러리를 사용하고 있기 때문에 기존 json 문자열을 동물원 노드에서 가져옵니다.

# gets the data from zookeeper
data, stat = zk.get(some_znode_path)
jsonStringA = data.decode("utf-8")

인쇄하면jsonStringA이런 느낌이에요.

{"error_1395946244342":"valueA","error_1395952003":"valueB"}

하지만 만약 내가 한다면print json.loads(jsonString)이렇게 출력됩니다.

{u'error_1395946244342': u'valueA', u'error_1395952003': u'valueB'}

여기서jsonStringA기존 JSON String을 갖게 됩니다.이제 다른 키와 값의 페어를 추가해 둘 필요가 있습니다.jsonStringA-

다음은 내 Python 코드입니다.

# gets the data from zookeeper
data, stat = zk.get(some_znode_path)
jsonStringA = data.decode("utf-8")

timestamp_in_ms = "error_"+str(int(round(time.time() * 1000)))
node = "/pp/tf/test/v1"
a,b,c,d = node.split("/")[1:]
host_info = "h1"
local_dc = "dc3"
step = "step2"

기존 데이터jsonStringA사육사에게서 추출한 후 이렇게 될 것이다.

{"error_1395946244342":"valueA","error_1395952003":"valueB"}

이제 이 키와 값의 쌍을jsonStringA-

"timestamp_in_ms":"Error Occured on machine "+host_info+" in datacenter "+ local_dc +" on the "+ step +" of process "+ c +"

즉, 아래 키와 값의 쌍을 병합해야 합니다.

"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"

최종 JSON String은 다음과 같습니다.

{"error_1395946244342":"valueA","error_1395952003":"valueB","error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}

이게 가능한가요?

a 와 b 가 Marge 하는 딕셔너리인 경우:

c = {key: value for (key, value) in (a.items() + b.items())}

문자열을 python 사전으로 변환하려면 다음을 사용합니다.

import json
my_dict = json.loads(json_str)

업데이트: 문자열 사용 전체 코드:

# test cases for jsonStringA and jsonStringB according to your data input
jsonStringA = '{"error_1395946244342":"valueA","error_1395952003":"valueB"}'
jsonStringB = '{"error_%d":"Error Occured on machine %s in datacenter %s on the %s of process %s"}' % (timestamp_number, host_info, local_dc, step, c)

# now we have two json STRINGS
import json
dictA = json.loads(jsonStringA)
dictB = json.loads(jsonStringB)

merged_dict = {key: value for (key, value) in (dictA.items() + dictB.items())}

# string dump of the merged dict
jsonString_merged = json.dumps(merged_dict)

하지만 일반적으로 당신이 하려고 하는 것은 최선의 실천이 아니라고 말해야 합니다.python 사전을 조금 읽어보세요.


대체 솔루션:

jsonStringA = get_my_value_as_string_from_somewhere()
errors_dict = json.loads(jsonStringA)

new_error_str = "Error Ocurred in datacenter %s blah for step %s blah" % (datacenter, step)
new_error_key = "error_%d" % (timestamp_number)

errors_dict[new_error_key] = new_error_str

# and if I want to export it somewhere I use the following
write_my_dict_to_a_file_as_string(json.dumps(errors_dict))

어레이를 사용하여 오류를 모두 보관하는 것만으로 이러한 모든 문제를 방지할 수 있습니다.

Python 3.5부터는 다음 두 개의 dict를 병합할 수 있습니다.

merged = {**dictA, **dictB}

(https://www.python.org/dev/peps/pep-0448/)

그래서:

jsonMerged = {**json.loads(jsonStringA), **json.loads(jsonStringB)}
asString = json.dumps(jsonMerged)

기타.

두 json 문자열을 Python 사전에 로드한 후 결합할 수 있습니다.이것은 각 json 문자열에 고유한 키가 있는 경우에만 작동합니다.

import json

a = json.loads(jsonStringA)
b = json.loads(jsonStringB)
c = dict(a.items() + b.items())
# or c =  dict(a, **b)

json 개체를 병합하는 것은 매우 간단하지만 키 충돌을 처리할 때 몇 가지 에지 케이스가 있습니다.가장 큰 문제는 단순한 유형의 값을 가진 개체와 복잡한 유형(어레이 또는 개체)을 가진 개체와 관련이 있습니다.당신은 그것을 어떻게 실행할지 결정해야 합니다.chef-solo에 전달된 json에 대해 이 기능을 구현했을 때 선택한 것은 객체를 Marge하고 다른 모든 경우에 첫 번째 소스 객체의 값을 사용하는 것이었습니다.

델의 솔루션은 다음과 같습니다.

from collections import Mapping
import json


original = json.loads(jsonStringA)
addition = json.loads(jsonStringB)

for key, value in addition.iteritems():
    if key in original:
        original_value = original[key]
        if isinstance(value, Mapping) and isinstance(original_value, Mapping):
            merge_dicts(original_value, value)
        elif not (isinstance(value, Mapping) or 
                  isinstance(original_value, Mapping)):
            original[key] = value
        else:
            raise ValueError('Attempting to merge {} with value {}'.format(
                key, original_value))
    else:
        original[key] = value

첫 번째 케이스 뒤에 다른 케이스를 추가하여 목록을 확인하는 것도 가능합니다.리스트를 Marge 하는 경우, 또는 특정의 경우에 특수 키를 검출할 수 있습니다.

키와 값의 쌍을 json 문자열에 추가하려면 dict.update를 사용합니다.dictA.update(dictB).

고객의 경우는, 다음과 같이 됩니다.

dictA = json.loads(jsonStringA)
dictB = json.loads('{"error_1395952167":"Error Occured on machine h1 in datacenter dc3 on the step2 of process test"}')

dictA.update(dictB)
jsonStringA = json.dumps(dictA)

이 발생한다는 하십시오.dictBdictA.

합병이라니 무슨 뜻이죠?JSON 개체는 키 값 데이터 구조입니다.이 경우 키와 가치는 무엇입니까?새 디렉토리를 생성하여 오래된 데이터로 채워야 합니다.

d = {}
d["new_key"] = jsonStringA[<key_that_you_did_not_mention_here>] + \ 
               jsonStringB["timestamp_in_ms"]

머지 방법은 분명히 당신에게 달려 있습니다.

언급URL : https://stackoverflow.com/questions/22698244/how-to-merge-two-json-string-in-python